Call a function when a user presses enter in an NSSearchField?
Asked Answered
U

1

5

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?

Unity answered 6/2, 2011 at 1:59 Comment(0)
E
16

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.

Exempt answered 6/2, 2011 at 2:22 Comment(1)
@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.