Dismissing The UITextField Keyboard

ios-keyboardLet’s say you are designing an iOS application which takes user input using a text field. When you add a text field to your storyboard and run your application, you will see that when you tap on the text field, the keyboard pops up automatically. But when you tap the return key, they keyboard doesn’t go away. As it turns out, the popping up of the keyboard is taken care of when you add the UITextField, but dismissing the keyboard is up to you. Here’s how you make it go away after you are done taking the input from the user:  

Add this in the ViewController.m file:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField 
{
    if (theTextField == self.myTextField) 
        [theTextField resignFirstResponder];

    return YES;
}

Here, myTextField is a UITextField defined in your .h file. Also, go to your storyboard file and make the following changes:

  1. Bring up the Assistant Editor and control-drag the text field from the storyboard file to the ViewController.h file
  2. Select the text field in the storyboard file and click the Connections Inspector.
  3. Now, make sure the “delegate” is assigned to “view controller” (and not just “view”). To do this, drag the empty circle in “delegate” to the bottom left icon on the storyboard (the one that says “View Controller”).

And you are all set! Go check your application and you will see that the keyboard goes away when you tap on the return key.

————————————————————————————————-

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s