2

I couldn't find anything up to date that solve this issue. How can I monitor something like arrow key presses while editing an NSTextField?

From what I looked up: - NSControlTextEditingDelegate functions are not called (and I wouldn't know how to use them) - NSTextFieldDelegate functions don't list something that would work here

gerbil
  • 859
  • 7
  • 26
  • Possible duplicate of [Recognize if user has pressed arrow key while editing NSTextField swift](https://stackoverflow.com/questions/29579092/recognize-if-user-has-pressed-arrow-key-while-editing-nstextfield-swift) – Willeke Dec 01 '17 at 12:54

2 Answers2

5

Set your text field's delegate:

textField.delegate = self

Add the following inheritance for protocols:

class MyTextField : NSTextFieldDelegate, NSControlTextEditingDelegate { ...

And implement the following:

   func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if commandSelector == #selector(moveUp(_:)) {
        ...
    } else if commandSelector == #selector(moveDown(_:)) {
        ...
    } else if commandSelector == #selector(insertNewline(_:)) {
        ...
    }
    return true
}

There are more in depth explanations in this link Recognize if user has pressed arrow key while editing NSTextField swift

gerbil
  • 859
  • 7
  • 26
0

keyDown doesn't seem to work with NSTextFields (it does for NSTextView), so what I did on my side was subclass either NSTextField or ViewController and add these methods:

import Cocoa

class MyTextField: NSTextField
{    
    override func keyUp(with event: NSEvent) {
        print("MyTextField keyUp key is %ld", event.keyCode)

        super.keyUp(with: event)            
    }
}

class MyTextView: NSTextView
{
    override func keyDown(with event: NSEvent) {

        print("MyTextView keyDown key is %ld", event.keyCode)

        super.keyDown(with: event)
    }    
}

class ViewController: NSViewController {

    override func keyUp(with event: NSEvent) {
        print("ViewController keyUp key is %ld", event.keyCode)

        super.keyUp(with: event)
    }
}
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215