Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyboardWillShow shows a strange height the first time

Tags:

ios

swift

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)
                }
            }
        }
    }   
like image 399
Mika Avatar asked Jan 07 '23 19:01

Mika


1 Answers

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.............. :)

like image 138
Krishna Raj Salim Avatar answered Jan 18 '23 23:01

Krishna Raj Salim