2

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?

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124

4 Answers4

6

From is answer, I found that I'm supposed to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey.

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124
4

you can get frame of keyboard by

override func viewDidLoad() {
    super.viewDidLoad()
    let center = NotificationCenter.default
    center.addObserver(self, selector: #selector(keyBoardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    // Do any additional setup after loading the view.
}
override func viewDidDisappear(_ animated: Bool) {
    let center = NotificationCenter.default
    center.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}



func keyBoardDidShow(_ notification:Notification)
{
    print((notification.userInfo?["UIKeyboardBoundsUserInfoKey"] as! CGRect).height)
}
Devil Decoder
  • 966
  • 1
  • 10
  • 26
0

Just import this library into your project. It will handle each and everything automatically.

aBilal17
  • 2,974
  • 2
  • 17
  • 23
-1

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