Coding on the iPhone is mostly a pleasant experience. XCode is a really nice IDE and I’ve come to like it (though I do fall back to Vim on occasion, see previous post about that). It’s the little things that really get you though! For instance, having the keyboard go away when it should. Another thing is when the text field is covered by the keyboard. Both are irritating and can be solved using the UITextFieldDelegate. Below is some code I’ve pasted into a few UIViewControllers! You can tweak that “100” number based on how much you want your view to move up to clear the keyboard.
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.25];
CGRect rect = [self.view frame];
rect.origin.y -= 100;
[self.view setFrame:rect];
[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.25];
CGRect rect = [self.view frame];
rect.origin.y += 100;
[self.view setFrame:rect];
[UIView commitAnimations];
}
To make sure these get called, you’ll want to do something like this in your “viewDidLoad” method.
[yourTextFieldUI setDelegate:self];
Thanxs man it simply works
Nice one, thanks for the tip. And if you’re looking to make the keyboard appear directly, it’s here:
http://bcaccinolo.wordpress.com/2010/12/28/uitextfield-with-the-keyboard-automagically/