iProgrammer Tip #4: Dismiss keyboard from UITextField in response to ‘return’ in keyboard

Jun 05 2009

Lets say you have  a UI with a UITexttField and a UIButton which does some action on the text you entered.

If the user can see the Button while the keyboard is up, its all well and good!

But what if the button gets under the keyboard and you dont have the ScrollView capability to push up the button in viewport?

I had run into such a situation and the trick i used was handling the optional delegate method  textFieldShouldReturn

1. In the header file of your viewcontroller, state that it conforms to UITextFieldDelegate

@interface myViewController : UIViewController <UITextFieldDelegate>

{

IBOutlet UITextField* myTextField;

IBOutlet UIButton* myButton;

}

- (IBAction) click;

@end

2. Tell the textfield that your viewcontroller is the delegate (preferably in viewDidLoad)

- (void)viewDidLoad

{

[super viewDidLoad];

myTextField.delegate = self;

}

3. Finally implement the optional delegate method as

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];

return NO;

}

Thats it! Now when you press return or any of those custom return key ( mostly set to Go / Done / Search, others will work too ofcourse! )

No responses yet

Leave a Reply

You must be logged in to post a comment.