1
votes

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

2

2 Answers

5
votes

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

0
votes

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)
    }
}