我正在使用键盘扩展应用,我需要默认键盘的高度。
为了获得KeyBoard的高度,我尝试了几十个解决方案like this,但是Selector函数永远不会被调用。 有没有其他方法可以找到默认键盘的高度?
答案 0 :(得分:0)
此代码将显示键盘的高度 -
func showKeyboard(notification: NSNotification) {
if let sizeOFkeyboard = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
let keyboardHeight = keyboardSize.height
}
}
答案 1 :(得分:0)
这对我来说非常适合 Swift 4.1 :
var keyboardHeight: CGFloat = 0.0
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
// Register Notification, To know When Key Board Appear.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
// Register Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
// De register the notifications
NotificationCenter.default.removeObserver(self)
}
// MARK: - Keyboard Events
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
keyboardHeight = keyboardRectangle.height
}
// use keyboard duration if needed (to animate your view)
let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double
}
@objc func keyboardWillHide(_ notification: Notification) {
let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double
}