views:

167

answers:

3

I've been looking all over for a simple example of how to have an action (or button) be triggered when the enter key is hit in the text field.

Should I subclass the text field? Would I need to set a delegate to call the action I need? Is there a way to catch the event in my main window controller class?

If you could even just point me to the right direction that would be great. Thanks.

A: 

You need to set the delegate of the text field, then do your action in (BOOL)textFieldShouldReturn:(UITextField *)textField. For instance:

-(void)viewDidLoad {
    UITextField *field = //etc
    field.delegate = self;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //do stuff here
    return YES;
}

EDIT: Oops, sorry, didn't see you're programming for mac. Ignore the above.

eman
+1  A: 

Just connect an IBAction of your controller class with a text field. The action should be called with you hit enter or leave the text field with Tab or Mouse.

Holli
+1  A: 

To get action after you hit enter just write an IBAction in your window controller and connect to your text field. If you want more like your method should be called when you focus on text field and leave the text field you need to set delegate(See here).

regards
Devara Gudda

Devara Gudda
Hi,Thanks I've done that but how do I filter out for the enter key because when they focus or blur from the text field the action is triggered too.THanks
Chris
To get notification when the editing is complete(either enter key or tab key is hit) the delegate class controlTextDidEndEditing method is called, there you can trigger the action. If you want your action to be triggered for only enter key then you have to either write custom formatter or customized NSTextfield class.
Devara Gudda
THanks Gudda. I actually just found out you can have it send the action only on enter as described here: http://mojomonkeycoding.com/2009/11/14/calling-an-action-when-hitting-return-in-an-nstextfield/. So thankfully no need to subclass.
Chris