How to get UIKeyboard size with iOS

You can get the keyboard size from the userInfo dictionary using the UIKeyboardFrameBeginUserInfoKey and the UIKeyboardFrameEndUserInfoKey instead.

These two keys return a NSValue instance containing a CGRect that holds the position and size of the keyboard at both the start and end points of the keyboard’s show/hide animation.

Edit:

To clarify, the userInfo dictionary comes from an NSNotification instance. It’s passed to your method that you register with an observer. For example,

- (void)someMethodWhereYouSetUpYourObserver
{
    // This could be in an init method.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                    selector:@selector(myNotificationMethod:) 
                    name:UIKeyboardDidShowNotification 
                    object:nil];
}

- (void)myNotificationMethod:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}

Edit 2:

Also, please don’t forget to remove yourself as an observer in your dealloc method! This is to avoid a crash that would occur when the notification center tries to notify your object after its been freed.

Leave a Comment