如何获得键盘的高度,包括swift 4中的建议栏

时间:2018-06-08 11:44:57

标签: ios swift keyboard

我用过:

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
      }
}

要更改以获得键盘的高度,但高度不包括建议栏如何获取键盘高度的值加上建议栏的高度?

4 个答案:

答案 0 :(得分:1)

使用UIKeyboardFrameEndUserInfoKey代替UIKeyboardFrameBeginUserInfoKeyUIKeyboardDidShow代替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
            }

        }

答案 1 :(得分:1)

首先,您需要注册键盘可见时触发的通知。

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

以方法获取键盘高度...

@objc func keyboardWillShow(_ notification: Notification) {

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

答案 2 :(得分:0)

请尝试使用UIKeyboardDidShow

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

只要键盘出现在屏幕上,您就会在keyboardWasShown方法中获得回调,

@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
    }
}

答案 3 :(得分:0)

使用0代替UIKeyboardFrameEndUserInfoKey返回正确的键盘高度。 例如,如果键盘没有工具栏,它将返回216.0高度。使用工具栏-260.0