how to get the height of the keyboard including th

2020-08-09 08:01发布

问题:

I used :

NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

@objc func keyboardWillShow(notification: NSNotification) {
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
      let keyboardHeight : Int = Int(keyboardSize.height)
      print("keyboardHeight",keyboardHeight)
      KeyboardHeightVar = keyboardHeight
      }
}

to change to get the height of the keyboard, but the height doesn't include the suggestions bar. How do I get the value of the keyboard height plus the suggestions bar height?

回答1:

Using the UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey returns the correct keyboard height. For example, if the keyboard without the toolbar, it returns 216.0 height. With the toolbar - 260.0



回答2:

Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey and UIKeyboardDidShow instead of UIKeyboardWillShow.

NotificationCenter.default.addObserver(self, selector: 

#selector(keyboardWillShow), name: .UIKeyboardDidShow, object: nil)
    @objc func keyboardWillShow(notification: NSNotification) {

            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                let keyboardHeight : Int = Int(keyboardSize.height)
                print("keyboardHeight",keyboardHeight)
                KeyboardHeightVar = keyboardHeight
            }

        }


回答3:

Try using UIKeyboardDidShow instead.

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

You'll get the callback in keyboardWasShown method whenever the keyboard is appear on the screen,

@objc func keyboardWasShown(_ notification : Notification)
{
    let info = (notification as NSNotification).userInfo
    let value = info?[UIKeyboardFrameEndUserInfoKey]
    if let rawFrame = (value as AnyObject).cgRectValue
    {
        let keyboardFrame = self.reportItTableView.convert(rawFrame, from: nil)
        let keyboardHeight = keyboardFrame.height //Height of the keyboard
    }
}


回答4:

First you need to register for notification that triggered when keyboard will be visible.

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

Get keyboard height in method...

@objc func keyboardWillShow(_ notification: Notification) {

 if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
 }
}