ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

iOS | How -To Programmatically Dismiss the UI Keyboard on IPhone or iPad Apps

Updated on July 28, 2012
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building software applications including iOS and Android apps.

The IOS app keyboard is a display qwerty keyboard that is automatically displayed when a user places the cursor in an enabled UITextField. Although the keyboard is automatically enabled, it is up to the developer to dismiss the keyboard when the user is finished entering data in a UITextField.

Actually it is quick easy to dismiss the keyboard once you know the basics. The IOS keyboard responds to events from the user. You can make the keyboard move to the background when the “return” button is pressed on the keyboard; you can also make the keyboard dismiss when the user moves the focus to another UITextField or presses a button on the UI. You can also make the keyboard close using finger gestures like a swipe.

In this tutorial, I will demonstrate these three use cases and this should give you all the building blocks to devise other methods of dismissing the keyboard in your own apps.

1- Dismiss Keyboard on UITextField Exist

This first example to demonstrate how to make the keyboard move to the background when a UITextField loses focus. Start by create a new project like a Single-View Application. Make sure the Storyboard and ARC (Automatic Reference Counting) is selected in the Options page. Next open the storyboard and add two TextFields and labels (optional). See Figure 1 below.

Creating Your IOS Project
Creating Your IOS Project

Select the first TextField and open the Attributes inspector. In the TextField properties, you will notice a Keyboard field. Leave the value at Default. You can choose other options like a numerical pad depending on your needs but this example the Default value is fine. In the Return Key field, select the “Done” value and also set the auto-enable the Return Key property. Repeat the sample process for the second TextField. At this point your UI should look something like Figure 2.

Configure the Keyword in the Storyboard
Configure the Keyword in the Storyboard

If you run your app right now and place your cursor in one of the two TexFields you should see the keyboard displayed on screen like in the following Figure 3.

Run the App and Display the Keyboard
Run the App and Display the Keyboard

To make the keyboard dismiss when TextField looses focus you will need to add a Delegate from the TextField to the View Controller Object . That is the yellow globe in the black bar at the bottom of the View Controller. To create a Delegate drag + drop a connection to the globe (Figure 4).

Creating Delegates
Creating Delegates

When you release the mouse button, a popover will appear. Simply select the Delegate option (Figure 5).

Setting the Outlet Delegate in the Dock
Setting the Outlet Delegate in the Dock

Repeat the same process for the second UITextField. Once that is complete, open the Assistant Editor and add two IBOutlets to the ViewController header file one for each UITextField and an IBAction for the button. If you help this operation, read this tutorial on creating Connection and Delegates. Your header field should look like Figure 6.

Adding IBOutlets and IBAction
Adding IBOutlets and IBAction

Now open the View Controller implementation file (.m) and add the following code to dismiss the keyboard:

-(BOOL)textFieldShouldReturn:(UITextField *)textfield{
if(textfield == self.FirstTextField){
[textfield resignFirstResponder];
[textfield resignFirstResponder];
return YES;

The textFieldShouldReturn method is defined in the UITextField class. It responds to the delegate that you created earlier and checks to see which UITextField is calling the method and dismisses the keyboard accordingly.

This is nice and simple. When the use click on the “Done” button on the keyboard, the keyboard moves to the background.

2-Dismiss Keyboard Using a Button

This second example builds on the first and basically uses the same code as in the first example. Open the implementation again and copy the following code to the IBAction method we create above:

- (IBAction)DismissButton:(id)sender {
[self.FirstTextField resignFirstResponder];
[self.SecondTextField resignFirstResponder];


In the above code, the delegate checks to see which UITextField is active (has the focus) and dismisses the keyboard by call the resignFirstResponder for the appropriate delegate call.

If you run the code and enter some text in one of the field and click on the “Dismiss Keyboard” button, the keyboard will move to the background as before.

3- Use Gestures to Dismiss Keyboard

This third and final example will dismiss the keyboard based on a gesture from the user. To make this work add a Swipe Gesture Recognizer (Figure 7). You will find these under Gesture Recognizers in the Object Library.

Adding a Swipe Gesture Recognizer
Adding a Swipe Gesture Recognizer

To respond to swipes in both directions, you would need two Swipe Gesture Recognizers but for out example we will only use one to detect a downward swipe. First drag and drop a Swipe Gesture Recognizer on to the View Controller. It will automatically add itself to the Scenes Dock (Figure 8).

Swipe Object in the Dock
Swipe Object in the Dock

Open the header file using the Assistant Editor and drag a connection from the Swipe to the header file (Figure 9). In the Popover change the Connection to Action, prove a name for your method and change the type to UISwipeGestureRecognizer. Click “Connect” create the method and enable the connection (Figure 9).

Adding IBAction for Swipe
Adding IBAction for Swipe
Configure the Swipe IBAction
Configure the Swipe IBAction

One more step in our Swipe configuration. Select the Swipe in the Dock and switch to the Attributes assistant and select the type of swipe to perform. You can select “Up”, “Down”, “Left” or “Right”. For this example, select “Down”. Also leave the Touches at 1. This determines the number of fingers to use for your swiping (Figure 10).

Configure the Swipe Gesture Recognizer
Configure the Swipe Gesture Recognizer

Now add a Delegate for our Swipe. Open the storyboard again and drag a connection to the View Controller Object in the Dock. Choose the method you just create in the Outlet popover. Now the Swipe will respond to your finger movements (Figure 11).

Add the Delegate for the Swipe Gesture Recognizer Action
Add the Delegate for the Swipe Gesture Recognizer Action

All is needed now to add some code to your new method. In this example, my method is called closeKeyboard and here is the code for it:

- (IBAction)CloseKeyboard:(id)sender {
[self.FirstTextField resignFirstResponder];
[self.SecondTextField resignFirstResponder];

If you run your app again, use the mouse pointer and drag the pointer downwards and release the mouse button. The keyboard will dismiss.

This covers most of the use cases for dismissing the keyboard. You can implement and adapt this code in this tutorial to fit your needs. Also build on these examples to build use the keyboard in other ways.


    0 of 8192 characters used
    Post Comment

    • klanguedoc profile image

      Kevin Languedoc 5 years ago from Canada

      Hi Keith. Heads up to you. There is a bug in my sorry. The code doesn't check to see which field has focus so the first condition is always true. I will work out a fix.

      Sorry about that.


    • profile image

      Keith 5 years ago from Alberta, Canada

      Hi Kevin,

      I cannot get the keyboard to dismiss with the button after entering text in the second textfield, it does dismiss with the button after entering text in the first textfield. Seems like the else statement would take care of that in the "(IBAction)DismissButton" but it does not.



    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: ""

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)