Search code examples
iosswiftkeyboard-eventsuikeyboardnotificationcenter

How to reliably get keyboard height in iOS Swift?


I have this code to detect when keyboard is shown and get its height.

@objc func keyboardWasShown (_ notification: Notification) {
    let keyboardSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size;
    print ("KEYBOARD SIZE: \(keyboardSize.height)");
}

At first, when I first time tap on a UITextView to make it first responder, the console showed 271.0 point.

Then I tap on the view to dismiss the keyboard. And then I tap again on the UITextView. Now it's showing 226.0 point.

There's no change to the keyboard layout on the first and subsequent trial. At first I always get 271, and then the next are always 226. The correct one is 271.

Why is this happening? And how to fix it?


Solution

  • don't know your exact scenario but try to use IQKeyboard it will deal with all your problems.