Lorenzo B
Lorenzo B

Reputation: 33428

iOS Programming: UITextField, listen for unfocus event

How can I listen for unfocus event in UITextFiekd?

I would create a sort of handler that is activated when my text field lost the focus. For example, if I click into another part of the application, that listen registers the text inside the UITextField automatically.

Thank you.

Upvotes: 1

Views: 4530

Answers (3)

Stephen Darlington
Stephen Darlington

Reputation: 52565

Two steps. First, define a delegate. Second, implement the textFieldDidEndEditing: delegate method. This selector is called when

the text field resigns its first responder status.

This is iOS-speak for losing focus. The documentation is here.

Upvotes: 0

Sabobin
Sabobin

Reputation: 4276

You could add a custom notification to the default notification center singleton.

Start by setting up a method in your text fields superviews view controller that contains code that you want to be executed when your text field goes out of view:

-(void)textFieldLostFocus{
    //do some work here... 
}

Then add your notification observer to the default notification center. (u can put this in viewDidLoad)

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldLostFocus) 
                                                 name:@"TextFieldDidLoseFocus" object:nil];

And then inside the UITextfield's superviews view controller add this:

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TextFieldDidLoseFocus" object:self userInfo:nil];
}

When the view goes out of view, your custom method will be called by the notification center.

Upvotes: 0

Nick Weaver
Nick Weaver

Reputation: 47241

There is a UITextFieldTextDidEndEditingNotification when the textfield resigns as first responder. You can also make use of the delegate method textFieldDidEndEditing:.

Upvotes: 2

Related Questions