Call a function when a user presses enter in an NSSearchField?

3k views Asked by At

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?

1

There are 1 answers

1
AudioBubble On BEST ANSWER

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.