Close the keyboard on UITextField
Asked Answered
Y

4

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?
Yerga answered 21/1, 2011 at 17:9 Comment(0)
O
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;
}
Osmosis answered 21/1, 2011 at 18:23 Comment(1)
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.Kolk
O
23

Inherit UITextFieldDelegate protocol In viewDidLoad method set:

yourTextField.delegate = self
Implement the delegate method below:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{ 
   [yourTextField resignFirstResponder];
   return NO;
}
Ornie answered 14/4, 2011 at 1:25 Comment(1)
Remember that yourTextField.delegate = self generates a warning in XCode if you don't set to comply with <UITextFieldDelegate> in your class's header file.Neologize
E
1

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

Inside textFieldShouldReturn write [notificationTitle resignFirstResponder];

Ermines answered 21/1, 2011 at 18:22 Comment(0)
F
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.

Francophobe answered 21/1, 2011 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.