Using UITextField on the iPhone

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

Advertisements

2 thoughts on “Using UITextField on the iPhone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s