Wednesday, February 23, 2011

NSSearchField return, arrow key press notification

In Cocoa development environment you might find NSSearchField difficult to trap the enter key event.
Also it becomes difficult to get the arrow key movements events.


In order to get these things to work, you need to do some simple stuffs with IBOutlet. You just need to connect your controller class with the delegate of NSSearchField.


In the controller class use below code to get the job done:

-(BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector {
    NSLog(@"doCommandBySelector");
    BOOL result = NO;
    if (commandSelector == @selector(insertNewline:)) {
        // enter key pressed
        result = YES;
    }
    else if(commandSelector == @selector(moveLeft:)) {
        // left arrow key pressed
        [textView moveLeft:nil];
        result = YES;
    }
    else if(commandSelector == @selector(moveRight:)) {
        // right arrow key pressed
        [textView moveRight:nil];
        result = YES;
    }
    else if(commandSelector == @selector(moveUp:)) {
        // up arrow key pressed
        result = YES;
    }
    else if(commandSelector == @selector(moveDown:)) {
        // down arrow key pressed
        result = YES;
    }
    return result;
}



Also, If you are interested in only in enter key event, set your controller class as the delegate of NSSearchField and implement the below method, which will be called when enter key is hit on the NSSearchField:
- (void)controlTextDidEndEditing:(NSNotification *)obj{
    NSLog(@"Enter key is hit");
}



* How to get the text out of NSSearchField:
The notification object(obj) in controlTextDidEndEditing method has the userInfo dictionary which contains the reference to the NSTextField in the NSSearchField control. Use below code to get the NSTextField object and the text in it.
NSTextView* textView = [[obj userInfo] objectForKey:@"NSFieldEditor"];
NSString *searchText=[textView string];





Let me know if something can be improved.

1 comment: