RSS

Receiving Enter & Arrow Key Presses From NSSearchField

The philosophy behind my Cocoa Code Snippets has been to post little quick tips on Cocoa routines and methods and such that have caused me to do some thinking/researching/tearing my hair out. This day’s tip came up in my development of the new Todos. With an NSSearchField you might find it difficult to find out when the user presses the enter key. You might also want to receive a notification when the user has pressed the arrow keys. To get this functionality, you’ll need to do just a little bit of work. In your Nib file, connect the NSSearchField to your controller class and select the outlet Delegate. In the controller class, you just need to add one method that responds to that delegate. Here is the complete function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
-(BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector {
    BOOL result = NO;
    if (commandSelector == @selector(insertNewline:)) {
		// enter pressed
		result = YES;
    }
	else if(commandSelector == @selector(moveLeft:)) {
		// left arrow pressed
		result = YES;
	}
	else if(commandSelector == @selector(moveRight:)) {
		// rigth arrow pressed
		result = YES;
	}
	else if(commandSelector == @selector(moveUp:)) {
		// up arrow pressed
		result = YES;
	}
	else if(commandSelector == @selector(moveDown:)) {
		// down arrow pressed
		result = YES;
	}
    return result;
}

Hopefully, the code looks pretty simple to you. This method will be called when certain selectors are called on your search field. Inside my function I test for which selector was chosen by using a simple compare if/else if/else structure and the @selector command. You can see what other selectors can be used to respond to other types of key presses by looking at the documentation for NSResponder under the section “Responding to Key Events.” I hope this snippet of code works fine for you. If you have any questions, please feel free to ask in the comments.

  • Walter Johnson
    Thanks. This works great for detecting the enter key. However, it also screws up the search field's ability to track recent searches. Anytime I press the down arrow to bring up my recent searches, no menu is displayed.
  • Walter Johnson
    As a follow-up to my previous comment, it's easier to detect the enter-key event by making your controller the search field's delegate and implementing controlTextDidEndEditing:. Pressing enter in a search field causes this notification to be sent. Granted, you won't be able to intercept the other keys...
blog comments powered by Disqus
« New Todos Icon : Draft One | Code Tip to Prevent Assignment Errors in Conditionals »