How to make return key on iphone make keyboard disappear?


I have 2 uiTextFields (e.g. username and password) but I cannot get rid of the keyboard when pressing the return key on the keyboard.

How can I do this?


asked May 31 ’11 at 15:57
  add comment

8 Answers

First you need to conform to the UITextFieldDelegate Protocol in your View/ViewController’s header file like this:

@interface YourViewController : UIViewController <UITextFieldDelegate>

Then in your .m file you need to implement the following UITextFieldDelegate protocol method:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];

    return YES;

[textField resignFirstResponder] makes sure the keyboard is dismissed.

Make sure you’re setting your view/viewcontroller to be the UITextField’s delegate after you init the textfield in the .m:

yourTextField = [[UITextField alloc] initWithFrame:yourFrame];
//Setting the textField's properties
//The next line is important!!
yourTextField.delegate = self; //self references the viewcontroller or view your textField is on
answered May 31 ’11 at 16:04
Hi Siddharth, I have done what you said above but it still doesn’t make the keyboard disappear. I’ve done theUITextFieldDelegate and then in my .m file, I have the above. Inside, [self.usernameField resignFirstResponder]; return YES;. Still not working though… Do you know why? Thanks. – K.Honda Jun 1 ’11 at 9:09
I have done this now. Thanks. –  K.Honda Jun 1 ’11 at 9:18
Cool… glad it worked –  Sid Jun 1 ’11 at 16:06
You can also implement the delegate in storyboard by clicking on the textfield, show Utilities panel, click Connections Inspector, drag delegate outlet onto the view controller. –  sguptaet Mar 20 ’13 at 16:13
@Sid Hi, this works great when the UITextFields are in a view. If I have UITextFields inside a scroll view, when tapped on a UITextField, even the keyboard doesn’t show up. So I changed the delegate to the scroll view. Now the keyboard shows up but when the return key is pressed, it doesn’t fire thetextFieldShouldReturn method. Any idea how to get around this? –  Isuru Mar 29 ’13 at 10:59

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s