How to get iOS keyboard height programmatically

July 19, 2015

How to get iOS keyboard height programmatically

There is a quite simple way to get iOS keyboard height programmatically. All you need to do is register for the notification UIKeyboardWillChangeFrameNotification and get the necessary property form the NSNotification dictionary that is going to be passed into the method. Afterwards you simply extract the height property you need. Here is the sample code:

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSLog(@"%f", [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);
}

Don't forget that since iOS8 you have autosuggestions on top of your keyboard that you can hide or show. This section is part of the keyboard and extends it's height accordingly. Make sure to remember this thing when modeling your view with autolayout!

I really advise to log the whole notification object to see what another useful information it has.

Comments

comments powered by Disqus