Capturing "up" and "down" keys pressed in NSTextField
You need to create an object to serve as the text field's delegate. This can be done either in code or, if it seems appropriate, in Interface Builder. You probably already have a controller responsible for this field and the stepper control, so that is a good candidate. This delegate object is what needs to implement the method you mentioned:
- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
This method will be called whenever the field editor* for the text field is asked to perform one of the NSResponder
action messages. The field editor asks its delegate, which is the text field, what it should do, and the field in turn asks its delegate, which is your object.
The commandSelector
argument holds the name of the action message. You can therefore test for the messages you are interested in (moveUp:
and moveDown:
in this case) and intercept them. You perform whatever actions you like and prevent the field editor or the text field from acting on the message.
- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor
doCommandBySelector:(SEL)commandSelector {
if( commandSelector == @selector(moveUp:) ){
// Your increment code
return YES; // We handled this command; don't pass it on
}
if( commandSelector == @selector(moveDown:) ){
// Your decrement code
return YES;
}
return NO; // Default handling of the command
}
*Briefly, an NSTextView
which handles input on behalf of the text field when the field is active.
if you want to capture shortcuts, you can also use code like this:
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
NSEvent *currentEvent = [[NSApplication sharedApplication]currentEvent];
if ((currentEvent.modifierFlags & NSCommandKeyMask) && (currentEvent.keyCode == kVK_Return)) { //command + enter to confirm
//do what you want
return YES;
}
return NO;
}
Try overriding NSResponder message like this:
- (BOOL)performKeyEquivalent:(NSEvent *)theEvent{
switch ([[theEvent charactersIgnoringModifiers] characterAtIndex:0]) {
case NSUpArrowFunctionKey:
// Increase by 5 here
return YES;
break;
case NSDownArrowFunctionKey:;
// Decrease by 5 here
return YES;
break;
default:
break;
}
return [super performKeyEquivalent:theEvent];
}