radex radex - 1 year ago 51
Objective-C Question

Capturing "up" and "down" keys pressed in NSTextField

I write an "Agent" Cocoa app where I have TextField in status icon's menu, it looks like this:

When you use the stepper, value inc-/decrements by 5. I want that when you have text field focused and you press "up" or "down" keys, the same happens -- value increases or decreases by 5.

I already figured out that I have to use

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector

But I'm really confused how I do that. Normally I would just do
sth.delegate = self;
and here I just don't know. Unfriendly language of Apple's documentation and my poor English don't help me. I tried to search for an answer but all people just pointed to
and my Google-searching abilities failed when I wanted to figure out how I use this delegate method.

Thanks a lot in advance. Please don't beat me ;)

Answer Source

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.