Showing posts with label UITextFieldDelegate. Show all posts
Showing posts with label UITextFieldDelegate. Show all posts

Tuesday, January 26, 2010

Disabling keyboard on UITextField selection

There are often cases where you want the look of UITextField but don't want to use the keyboard. There are a few hacky ways such as hidden buttons overlaying text fields, but I think this is the most intelligent way to disable the show of the UIKeyboard, and replacing it with something of your choice:


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 
// Make a new view, or do what you want here
UIDatePicker *pv = [[UIDatePicker allocinitWithFrame:CGRectMake(0,185,0,0)];
[self.view addSubview:pv];

return NO;
}

You'll need to be implementing UITextFieldDelegate, and you can catch this event prior to the framework showing the UIKeyboard. In the above example I am showing a UIDatePicker instead. Returning NO is what is making the keyboard not show, since we aren't actually letting the editing begin.

Making the keyboard disappear

So... I said this blog was going to be about basics, right? Well, here's a really basic concept that may elude some folks. If you have a UITextField on your view, and are implemented UITextFieldDelegate in your delegate class, perhaps you have noticed that after you enter some text using the keyboard for your field, the keyboard won't disappear when you hit return? Well, here's all you have to do:


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}

Since you are implementing the UITextFieldDelegate class, this method will be called on Return, your text field will give up focus, and the UIKeyboard will disappear. If you want to be more particular and a little safer in your method you can do the following:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  if(textField == [self yourTextField]) {
[textField resignFirstResponder];
  }
return YES;
}