键盘显示通知使用iOS11 Simulator调用两次

时间:2017-09-06 09:06:06

标签: ios swift xcode keyboard ios11

我使用UIKeyboardFrameEndUserInfoKey键获得键盘高度,如下所示:

let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)

如果我点按UITextView,键盘就会出现,并打印

258.0

然后我按⌘ + k,模拟器连接硬件键盘,因此模拟器上的软键盘关闭。

如果我按⌘ + k再次键盘,键盘显示通知会被调用两次并打印

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,则会显示结果...

result console image

1 个答案:

答案 0 :(得分:1)

不确定你是如何声明你的observer,但以下在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