6

When using a custom keyboard, keyboardWillShow is ran twice (normal behavior) the first the height is 0 but the second is the correct height in my case 667. The problem is that this is only true the second time the viewController is showed. The first time I get the strange output below.

Console the first time the view controller is opened:

keyboardSize CGRect (origin = (x = 0, y = 258), size = (width = 0, height = 2.8876618518302306E-314))

Console the second time the view controller is opened:

keyboardSize CGRect (origin = (x = 0, y = 0), size = (width = 0, height = 667))

My code:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)

func keyboardWillShow(notification: NSNotification) {
        if let userInfo = notification.userInfo {
            if let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
                if keyboardSize.height > 0 { //in case of custom keyborad
                    kbHeight = keyboardSize.height
                    self.animateTextField(true)
                }
            }
        }
    }   
Mika
  • 5,807
  • 6
  • 38
  • 83
  • 7
    Have you tried: `userInfo[UIKeyboardFrameEndUserInfoKey]`? Source: http://stackoverflow.com/questions/25874975/cant-get-correct-value-of-keyboard-height-in-ios8 – Caleb Aug 10 '15 at 16:04
  • Thanks this does solve the problem but I really want to understand the behavior. – Mika Aug 10 '15 at 16:10
  • There doesn't seem to be any documentation suggesting why the two heights would be different. It is probably just some bug. The `y` coordinate looks to be incorrect as well and is probably related to the same bug. – Caleb Aug 10 '15 at 16:21

1 Answers1

13

Change UIKeyboardFrameBeginUserInfoKey with UIKeyboardFrameEndUserInfoKey. Thats all:

func keyboardWillShow(notification: NSNotification) {
  if let userInfo = notification.userInfo {
    if let keyboardSize =  (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
      if keyboardSize.height > 0 { //in case of custom keyborad
        kbHeight = keyboardSize.height
        self.animateTextField(true)
                }
            }
        }
    }  

Keep coding.............. :)

Krishna Raj Salim
  • 7,331
  • 5
  • 34
  • 66