Thursday, April 01, 2010

Dismiss IPhone keyboard in text field control

By default, IPhone keyboard will not dismiss automatically after user click on the done button or touch other control or view. IPhone developer has to code this behaviour into the control.

The IPhone keyboard will only be dismissed after a resignFirstResponder message is send to the control.
Eg.
                 [textField resignFirstResponder];

There are probably many ways to add this message to the viewController code.  Below show two of them:

1. Implement  the textFieldShouldReturn delegate for the UITextField. Iphone will pass a message to textFieldShouldReturn method when the keyboard's done button is pressed. Call the send the resignFirstResponder message to the active UITextField will dismiss the keyboard. The following section outline the steps to accomplish this:

a)  Add to the viewController.h interface file to specify that it will implement the delegate textFieldShouldReturn method.
Eg.
@interface sampleViewController : UIViewController  
                                                    <UITextFieldDelegate>     
  // add this line to implement textFieldShouldReturn method, when more than one use comma

b) Implement the textFieldShouldReturn method in the .m implement file.
Eg.
-(BOOL)textFieldShouldReturn:(UITextField *)thisTextField  {
    [thisTextField resignFirstResponder];
    // add code to process the input if needed
    return TRUE;
}

c) link the textField to the class that implement the method.
Eg.


2. Override the touchesBegan method. Iphone will send the touchesBegan message when the view is being touched. In the overrided touchesBegan method, send the resignFirstResponder message to the active UITextField will dismiss the keyboard.
Example add the following code to the viewController:
- (void)touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event {
    if( textField.editing) {   // UITextField.editing will return true if it is in the editing mode

       [textField resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];     // call the default touchesBegan method
}

No comments:

Post a Comment