When the user taps on a text field and the keyboard appears, sometimes people write code such as the following to resize their view:
#define KEYBOARD_HEIGHT 216
self.tableView.moHeight -= KEYBOARD_HEIGHT;
self.textView.moTop -= KEYBOARD_HEIGHT;
Don't do that! Keyboard height can be different for different languages and input methods. Instead do this (and with a dash of animation):
//Do this earlier, eg. in -initWithFrame:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
-(void)keyboardWillShow:(NSNotification*)aNotification {
CGRect keyboardBounds;
[[aNotification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
self.tableView.moHeight -= keyboardBounds.size.height;
self.textView.moTop -= keyboardBounds.size.height;
} completion:NULL];
}
(The moHeight
and moTop
are just convenience properties I have added to avoid dealing directly with CGRect
).
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.