How to determine the height of the keyboard in iOS

Keyboards in iOS can have various sizes. Not only can a keyboard be presented in portrait or landscape, on various devices with a plethora of screen sizes, and users may have QuickType enabled or disabled. Too many variables for hard coding.

Lucky for us, we can check all kinds of properties about a keyboard by dissecting the dictionary that is passed with the notifications mentioned in my previous post. If you recall, we can check when a keyboard appears or disappears using an observer. Let’s take a look at that notification when the keyboard is presented, and we can extract the height like this:

- (CGFloat)grabKeyboardHeight:(NSNotification *)notification {
    
    // grab keyboard size
    NSDictionary *userInfo = notification.userInfo;
    NSValue *keyFrame = [userInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = keyFrame.CGRectValue;
    CGFloat height = keyboardFrame.size.height;
    
    return height;
}

The keyboard’s width can be determined in much the same way. The dictionary holds many other interesting goodies, for example how long it takes iOS to animate it onto the screen:

- (NSTimeInterval)grabAnimationDuration:(NSNotification *)notification {
    
    // find out how long the keyboard animation lasts
    NSDictionary *userInfo = notification.userInfo;
    NSTimeInterval duration = [[userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    
    return duration;
}

Apple has the full list if interesting objects for us to play with:





Leave a Reply