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
}

2 comments:

  1. Nice and very helpful information i have got from your post. Even your whole blog is full of interesting information which is the great sign of a great blogger.

    Lenovo - IdeaPad 15.6" Laptop - 6GB Memory - 1TB Hard Drive - Dark Chocolate

    Lenovo - 14" Notebook - 4 GB Memory - 320 GB Hard Drive - Black

    ReplyDelete
  2. Buy & sell new and used iPhones.
    Wide selection of new and used iPhones for sale.
    More at www.postallads4free.com

    ReplyDelete