Writing iOS 7 Code to Hide the Keyboard

From Techotopia
Revision as of 14:43, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

Jump to: navigation, search
PreviousTable of ContentsNext
Creating an Interactive iOS 7 AppAn Introduction to Auto Layout in iOS 7


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


When the user of an iOS 7 app is required to enter data (typically as a result of touching a text input view such as a text field) the keyboard automatically appears on the screen. As illustrated in the preceding chapter, however, the keyboard does not automatically go away when the user has finished typing.

If you have experience of using other iPhone or iPad apps you will have noticed that pressing the Return key on the keyboard or tapping anywhere on the background of the user interface usually causes the keyboard to recede from view. In actual fact, the developers of these applications had to write some code specifically to implement this functionality. In this chapter we will cover the steps necessary to implement this behavior in your own iOS 7 apps.


Contents


Creating the Example App

If you are reading this book sequentially you can perform the steps outlined in this chapter using the example application outlined in the previous chapter. For those who are dipping into this book as a reference source and would like to try out a simple example it will first be necessary to create a sample application.

Begin by launching Xcode and creating a new Single View based iPhone or iPad iOS application product named HideKeyboard with a matching class prefix. From within the main Xcode window select the Main.storyboard file to edit the user interface. Within the Interface Builder panel drag a Text Field object from the Object Library panel (View -> Utilities -> Show Object Library) onto the View area.

Now that we have the user interface designed, we need to create an outlet so that we can reference our text field from our view controller code. Within the main Xcode window, display the Assistant Editor, make sure it is displaying the contents of the HideKeyboardViewController.h file and Ctrl-click and drag from the text field object to a point below the @interface line in the Assistant Editor panel. In the resulting connection dialog, name the outlet textField and click on Connect. Select the HideKeyboardViewController.h file and verify that the outlet has been established correctly:

#import <UIKit/UIKit.h>

@interface HideKeyboardViewController : UIViewController 

@property (strong, nonatomic) IBOutlet UITextField *textField;
@end

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Hiding the Keyboard when the User Touches the Return Key

The next step is to wire up our application so that the keyboard is dismissed when the user touches the keyboard Return key. To do so, we need to write a method that will resign the first responder on the text field (in other words hide the keyboard) when the return key is pressed.

Begin by editing the HideKeyboardViewController.h interface file to declare the method which we will name textFieldReturn:

#import <UIKit/UIKit.h>

@interface HideKeyboardViewController : UIViewController 

@property (strong, nonatomic) IBOutlet UITextField *textField;
-(IBAction)textFieldReturn:(id)sender;
@end 

Having declared the method we now need to implement it in the HideKeyboardViewController.m implementation file:

#import "HideKeyboardViewController.h"

@interface HideKeyboardViewController ()

@end

@implementation HideKeyboardViewController

-(IBAction)textFieldReturn:(id)sender
{
    [sender resignFirstResponder];
}
.
.
.
@end

In the above method we are making a call to the resignFirstResponder method of the object that triggered the event. The first responder is the object with which the user is currently interacting (in this instance, the virtual keyboard displayed on the device screen).

Having written the code for our method we now need to wire up our user interface so that it gets called at the appropriate time. We will perform this task in Interface Builder, so select the Main.storyboard file once more.

Select the text field in the view and display the Connections Inspector (View -> Utilities -> Connections Inspector) in the right hand panel. Click on the circle to the right of the Did End on Exit event, drag the line to the view controller icon located in the panel immediately beneath the view canvas in the Interface Builder panel as shown in Figure 12-1:


Connecting the Did End On Exit event to a view controller action method in Xcode 5

Figure 12-1


Release the line and select the textFieldReturn method from the list of available methods in the resulting panel.

Click on the Run button in the Xcode toolbar. When the application appears in the iOS Simulator, select the text field so that the keyboard appears and then touch the Return key. The keyboard should subsequently disappear from view.


Hiding the Keyboard when the User Taps the Background

The second mechanism for hiding the keyboard involves wiring up an event to be called when the user touches the background view of the screen (or any view other than the text field). To achieve this, we will implement the touchesBegan event handler method on the view controller. This method will need to check that the object being touched by the user is not the textField itself. The method will then simply call the resignFirstResponder method of the textField to hide the keyboard:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([_textField isFirstResponder] && [touch view] != _textField) {
        [_textField resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

Save the code and then build and run the application. When the iOS Simulator starts up, select the text field so that the keyboard appears. Touching any area of the background should cause the keyboard to disappear.

Summary

Whilst the iOS onscreen keyboard appears automatically when the user is required to input information, the subsequent removal of the keyboard is left at the discretion of the application. Convention dictates that the keyboard be dismissed when the user touches the keyboard Return key (unless multi-line input is required) or when the background of the user interface is tapped. In this chapter we have explored and detailed the steps and code necessary to implement both of these functions.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Creating an Interactive iOS 7 AppAn Introduction to Auto Layout in iOS 7