我正在使用 UIKeyboardFrameEndUserInfoKey
键获取键盘高度,如下所示:
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
如果我点击 UITextView
,键盘会出现并打印
258.0
然后我按 ⌘ + k
,模拟器连接硬件键盘,因此模拟器上的软件键盘关闭。
如果我按 ⌘ + k
再次组合键盘,keyboardShow 通知会调用两次并打印
216.0
258.0
为什么键盘显示通知调用两次,为什么首先调用 216.0
?
更新
这是我的完整代码。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
let userInfo = notification.userInfo!
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight);
}
@objc func keyboardWillHide(notification: NSNotification) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如果我多次按 ⌘ + k
就会显示结果...
最佳答案
不太确定您是如何声明您的观察者
的,但以下内容在 Xcode 8 和 Xcode 9 beta (iOS 11) 中都可以正常工作。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
}
@objc func keyboardWillShow(sender: NSNotification) {
let keyboardHeight = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
}
更新:
刚刚测试了您的代码,它符合要求并且工作正常,您一定有其他干扰它的东西。
测试后的输出:
226.0
226.0
226.0
226.0
226.0
226.0
关于ios - 使用 iOS11 模拟器调用两次键盘显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071049/