24

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?
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
Francesc
  • 1,339
  • 4
  • 16
  • 34

4 Answers4

46

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;
}
Community
  • 1
  • 1
Lyle Pratt
  • 5,636
  • 4
  • 27
  • 28
  • 2
    If this is not yourTextField, shouldn't we return YES? For other fields we should get default behavior, since the questioner doesn't specify any special action. – Andrew Nov 12 '13 at 23:34
23

Inherit UITextFieldDelegate protocol In viewDidLoad method set:

yourTextField.delegate = self
Implement the delegate method below:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{ 
   [yourTextField resignFirstResponder];
   return NO;
}
Guilherme Defreitas
  • 1,044
  • 1
  • 10
  • 16
  • 2
    Remember that `yourTextField.delegate = self` generates a warning in XCode if you don't set to comply with `` in your class's header file. – Julian Jan 15 '12 at 01:04
1

Inherit UITextFieldDelegate protocol and implement textFieldShouldReturn:, that's you will catch "return" event.

Inside textFieldShouldReturn write [notificationTitle resignFirstResponder];

Martin Babacaev
  • 6,240
  • 2
  • 19
  • 34
0

Add a action target to the event Did End on Exit(UIControlEventEditingDidEndOnExit), in the target function remove the first responder from the text filed using resignFirstResponder. Adding action target

Note: 1. Nib --- give action to even Did End on Exit 2. In code add target action to the event UIControlEventEditingDidEndOnExit.

Girish Kolari
  • 2,515
  • 2
  • 24
  • 34