Nov 30, 2012

How to hide the keyboard when user taps the return key

     When user taps UITextField object, then soft keyboard appears from bottom. But there is no way to hide the keyboard by default. Let's make hide the keyboard when user taps the return key.

 

     We can be achieved in 4 steps.
  1. Set ViewController as delegate of UITextField
  2. Adopt UITextFieldDelegate Protocol
  3. Get a message of return key from UITextField
  4. Hide the keyboard

1. Set ViewController as delegate of UITextField

     UITextField object sends a message for its delegate when user taps the return key. First, we set VewController as the delegate. 

     Please open Xcode, and click a storyboard file. And drag from UITextField to ViewController while holding down the control key. There is a blue line on screen while you holding down the control key.



     Click "delegate" from pop up menu.


     OK. It's done. You can look see the connection of delegate on Utilities pane.



2. Adopt UITextFieldDelegate Protocol

     UITextField and its delegate communicate each other with UITextFieldDelegate Protocol. Adopt UITextFieldDelegate protocol to ViewController by writing following code.
#import <UIKit/UIKit.h>
@interface TaskViewController : UIViewController <UITextFieldDelegate>
@end
     UIViewController declared that is adopting UITextFieldDelegateProtocol itself.

3. Get a message of return key from UITextField

     UITextField sends "textfieldShouldReturn:" message to its delegate when user taps the return key.  Now, implement to this method to confirmation whether a message has actually arrived. Edit ViewController as below.

     xxxxViewController.h
#import <UIKit/UIKit.h>
@interface TaskViewController : UIViewController  <UITextFieldDelegate>

// ADD HERE
- (BOOL)textFieldShouldReturn:(UITextField *)textField;

@end

     xxxxViewController.m
#import "TaskViewController.h"

@interface TaskViewController ()

@end

@implementation TaskViewController

// ADD HERE
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
 NSLog(@"tapped return key!");
 return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
     Run this code, and tap UITextField. When you tap the return key, log is output in debug area.



4. Hide the keyboard

     Finally, add the process of hiding the keyboard. Edit textFieldShouldReturn: method as below.
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
 [textField resignFirstResponder];
 return YES;
}
     If we want to hide the keyboard, send resignFirstResponder: message to the keyboard object.

References - iOS Developer Library