Showing posts with label UITextField. Show all posts
Showing posts with label UITextField. Show all posts

Thursday, July 29, 2010

Using Next and Done with UITextFields and UIKeyboard

So you've probably seen in interface builder that its quite simple to pick which enter key you will use in your keyboard for a given UITextField. The minor complexity is that these different labels don't mean anything unless you add some code in your controller to handle the actions. Let's say you have three UITextFields:
  1. Username
  2. Password
  3. Email
You would want to set the first two to 'next' and the last to 'done' in interface builder. Then, you will need to implement UITextFieldDelegate in your View Controller, and use the following:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == txtUsername) {
[txtPassword becomeFirstResponder];
}
else if (textField == txtPassword) {
[txtEmail becomeFirstResponder];
}
[textField resignFirstResponder];
return YES;
}

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;
}