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