原文地址:http://dbachrach.com/blog/2008/02/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 . 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:
- -(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;
- }