iOS Dev Nugget 20 Do not hardcode keyboard height


Need to run a code review on your codebase? Hire me

When the user taps on a text field and the keyboard appears, sometimes people write code such as the following to resize their view:

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


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues