Close the keyboard on UITextField

Francesc picture Francesc · Jan 21, 2011 · Viewed 32.4k times · Source

I'm a newbie developing for iOS devices. I inserted an UITextField on InterfaceBuilder, and I assigned with the code:


@interface ComposeViewController : UIViewController {
 id <ComposeViewControllerDelegate> delegate;
 IBOutlet UITextField *notificationTitle;
}
How I could allow to close the keyboard when the user press the "Return" key?

Answer

Lyle Pratt picture Lyle Pratt · Jan 21, 2011

Set the Delegate of the UITextField to your ViewController, add a referencing outlet between the File's Owner and the UITextField, then implement this method:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   if (textField == yourTextField) {
       [textField resignFirstResponder];
   }
   return NO;
}