我用过:
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
}
}
要更改以获得键盘的高度,但高度不包括建议栏。 如何获取键盘高度的值加上建议栏的高度?
答案 0 :(得分:1)
使用UIKeyboardFrameEndUserInfoKey
代替UIKeyboardFrameBeginUserInfoKey
和UIKeyboardDidShow
代替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