Search code examples
iosobjective-cuitextfielduitextfielddelegate

UITextField lose focus event


I have an UITextField in a MyCustomUIView class and when the UITextField loses focus, I'd like to hide the field and show something else in place.

The delegate for the UITextField is set to MyCustomUIView via IB and I also have 'Did End On Exit' and 'Editing Did End' events pointing to an IBAction method within MyCustomUIView.

@interface MyCustomUIView : UIView { 

IBOutlet UITextField    *myTextField;

}

-(IBAction)textFieldLostFocus:(UITextField *)textField;

@end

However, neither of these events seem to get fired when the UITextField loses focus. How do you trap/look for this event?

The delegate for the UITextField is set as MyCustomUIView so I am receiving textFieldShouldReturn message to dismiss the keyboard when done.

But what I'm also interested in is figuring when the user presses some other area on the screen (say another control or just blank area) and the text field has lost focus.


Solution

  • I believe you need to designate your view as a UITextField delegate like so:

    @interface MyCustomUIView : UIView <UITextFieldDelegate> { 
    

    As an added bonus, this is how you get the keyboard to go away when they press the "done" or return buttons, depending on how you have set that property:

    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
      //This line dismisses the keyboard.       
      [theTextField resignFirstResponder];
      //Your view manipulation here if you moved the view up due to the keyboard etc.       
      return YES;
    }