Writing iOS 4 Code to Hide the iPhone Keyboard

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Creating an Interactive iOS 4 iPhone AppUnderstanding iPhone iOS 4 Views, Windows and the View Hierarchy

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 iPhone iOS 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 apps you will have noticed that pressing the Return key on the keyboard or tapping anywhere on the background of the user interface 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 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 View-based iPhone iOS application project called hideKeyboard. From within the main Xcode window double click on the hideKeyboardViewController.xib file to launch the Interface Builder tool. Within Interface Builder drag a Text Field object from the Inputs and Values section of the Library window onto the View window. Save the design and exit from Interface Builder.

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 select the hideKeyboardViewController.h file and edit it so that it appears as follows:

#import <UIKit/UIKit.h>

@interface hideKeyboardViewController : UIViewController {
        UITextField    *textField;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
@end

Be sure to save the changes before proceeding (File -> Save or Command+S). Next we need to synthesize the accessors for the new outlet in the hideKeyboardViewController.m implementation file:

#import "hideKeyboardViewController.h"
@implementation hideKeyboardViewController
@synthesize textField;
.
.
@end

Reload the hideKeyboardViewController.xib file into Interface Builder and connect the text field to the view controller outlet by holding down the Ctrl key while clicking and dragging with the mouse from the File’s Owner icon to the text field object in the View window. From the resulting menu select the textField outlet. Save the design and exit the Interface Builder tool.

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 {
        UITextField    *textField;
}
@property (nonatomic, retain) 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"
@implementation hideKeyboardViewController
@synthesize textField;

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

<google>ADSDAQBOX_FLOW</google> 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 iPhone 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 double click on the hideKeyboardViewController.xib file to load the file once more.

Once Interface Builder has loaded, select the text field in the view window and display the Connections Inspector window (Tools -> Connections Inspector or Command+2). Click on the circle to the right of the Did End on Exit event, drag the line to the File’s Owner icon and select textFieldReturn from the list of available methods.

Save the design, exit from Interface Builder and click on the Build and 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. We will begin the process by writing the action method to perform this task. From within Xcode select the hideKeyboardViewController.h file and add a declaration for our new backgroundTouched action method:

#import <UIKit/UIKit.h>

@interface hideKeyboardViewController : UIViewController {
        UITextField    *textField;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
- (IBAction)textFieldReturn:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
@end

Save the file, then open the hideKeyboardViewController.m file and implement the action by calling the resignFirstResponder method of our textField object:

#import "hideKeyboardViewController.h"
@implementation hideKeyboardViewController
@synthesize textField;
-(IBAction)textFieldReturn:(id)sender
{
        [sender resignFirstResponder];
}

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

<google>IOSBOX</google> Having written the code for our action method we now need to make sure it gets called when the user touches the background view. This involves some work in Interface Builder, so double click on the hideKeyboardViewController.xib file to invoke the tool.

In order to make the keyboard disappear we need to configure our user interface so that the action method gets called when the background view is touched by the user. By default, Interface Builder has given us an instance of the UIView class as the background to our interface. Unfortunately UIView instances are unable to respond to events so there is no way given the current configuration that we can trigger our action method. We must, therefore, change the class of the view to be an instance of the UIControl class. In the hideKeyboardViewController.xib window there is an icon labeled View located to the right of the File’s Owner and First Responder icons. This represents the main view of our interface. Select this icon and display the Identity Inspector (Tools -> Identity Inspector or Command+4) and within the inspector window change the Class setting from UIView to UIControl:


Changing the class of an iOS UIKit UIView instance to a UIControl to allow event handling


Now that we have changed the class of the background view to UIControl (which is itself a subclass of UIView) we will be able to set up a connection to our backgroundTouched action method. Within the window now entitled Control, select the background of the interface and display the Connections Inspector window. Click on the circle to the right of the Touch Down event and drag the connection line to the File’s Owner icon. Release the mouse button and select the backgroundTouched method from the resulting menu. Save the design, exit from Interface Builder and 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 iPhone 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 they keyboard be dismissed when the user touches the 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 4 iPhone AppUnderstanding iPhone iOS 4 Views, Windows and the View Hierarchy