Call a function when a user presses enter in an NSSearchField?
I am surprised that I can't find the answer to t开发者_如何学JAVAhis simple task. I just want the user to type in text, press enter, and have the application know what s/he typed. How would I do this?
NSSearchField
supports the action target mechanism, so simply hook it to a target/action. For instance, suppose you have the following action declared in your application delegate:
- (IBAction)searchAnswer:(id)sender;
In Interface Builder, ctrl-drag your search field to the application delegate object and choose the searchAnswer:
action. In its implementation, use -stringValue
to obtain the text typed by the user into the search field, e.g.
- (IBAction)searchAnswer:(id)sender {
NSLog(@"search answer: %@", [searchField stringValue]);
}
Note that by default the search field sends the action when the user pauses/stops typing, too. If you want it to send the action only when the user types Enter, choose the Sends Whole Search String
checkbox in the search field attributes inspector window.
精彩评论