Search code examples
cocoanstextfield

Detecting arrow/enter keys when editing NSTextField


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


Solution

  • 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