iOS 8 get keyboard height

29,036

Solution 1

The way you are doing it is correct but you might want to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey. The end user key is the frame of the keyboard when it is done animating and on the screen, thus you know it will be that frame, while the begin key might not always match what the keyboard frame will be when it is shown.

There might also need to be extra considerations on orientation of the device, I have not looked into that, but for portrait, it should work.

Solution 2

The correct way to do this is to use the inputAccesorryView property of the UITextField.

The inputAccessoryView is automatically added above the keyboard regardless of keyboard size.

As the documentation states:

The default value of this property is nil. Assigning a view to this property causes that view to be displayed above the standard system keyboard (or above the custom input view if one is provided) when the text field becomes the first responder. For example, you could use this property to attach a custom toolbar to the keyboard

See more information here https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

Share:
29,036
James
Author by

James

Hello there!

Updated on July 10, 2022

Comments

  • James
    James almost 2 years

    I'm having trouble reliably getting the actual height of the keyboard. I'm adding a custom toolbar that is meant to be placed directly above the keyboard. To do so with layout constraints, I've added a static space constraint between the bottom of the screen and the bottom of the toolbar. When the keyboard is displayed, I modify this constraint to be the height of the keyboard, which varies quite a bit in iOS 8.

    To resize the spacer, I currently use the following method that gets fired on UIKeyboardDidShowNotification

    -(void)keyboardDidShow:(NSNotification*)notification
    {
       CGFloat height = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].height;
    
       self.shimConstraint.constant = height;
       [self.view layoutIfNeeded];
    }
    

    This does resize the constraint correctly sometimes, but often the keyboard height returned is entirely incorrect. What is the best way to reliably get the height of the keyboard once it is displayed?

    EDIT: The application allows the user to switch between a number of different input fields. Some of them have autocorrect disabled, so the autocorrect bar may or may not be hidden, and incorrect heights are returned when switching fields.