I have many NSTextFields and I want to know, if the user has pressed one of the arrow keys while editing one of them. The function
override func keyDown(theEven
When text fields have the focus, they actually don't. Instead, a text view is added to the window on top of the text field and that text view is the first responder and handles all of the input and editing behaviors. The text view is known as the "field editor". The text field does not receive key down events; the text view does.
You could substitute a custom text view as the first responder for the text field and have that text view handle the key down events specially. However, it's probably easier to take advantage of the fact that the text field is the delegate for the text view. Depending on exactly what you're trying to achieve, you might implement -textView:willChangeSelectionFromCharacterRange:toCharacterRange:
, but that's not exclusively about arrow keys.
A more promising method might be -textView:doCommandBySelector:
. That's also not really about the arrow keys, but in some ways it's better. The arrow keys, and all other standard editing keys, operate by being translated through the key bindings system into command selectors. The command selectors represent the semantic operation being performed, like -moveUp:
. They are changed by modifier flags, so that Shift-up-arrow might generate -moveUpAndModifySelection:
.
Anyway, in -textView:doCommandBySelector:
, you can execute code based on the selector and either tell the text view not to do anything else (by returning YES
) or let the text view do its normal thing in addition (by returning NO
). (Obviously, return NO
for anything that you don't care about.)