I am surprised that I can't find the answer to this 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?
Call a function when a user presses enter in an NSSearchField?
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.
@Flafla2: Target/action is at a higher level than key or mouse events. A field may send its action even if the user has no Enter key, or no keyboard at all. A button may send its action even if the user has no mouse. Using target/action means you can receive the action regardless of what interface devices the user has or hasn't. –
Bascule
© 2022 - 2024 — McMap. All rights reserved.