how to get the height of the keyboard including th

2020-08-09 08:16发布

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?

4条回答
【Aperson】
2楼-- · 2020-08-09 08:41

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
 }
}  
查看更多
贪生不怕死
3楼-- · 2020-08-09 08:44

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
            }

        }
查看更多
何必那么认真
4楼-- · 2020-08-09 08:47

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
    }
}
查看更多
干净又极端
5楼-- · 2020-08-09 08:57

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

查看更多
登录 后发表回答