【问题标题】:Keyboard show notification called twice using iOS11 Simulator使用 iOS11 Simulator 调用两次键盘显示通知
【发布时间】:2018-02-14 16:45:58
【问题描述】:

我正在使用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 会显示结果...

result console image

【问题讨论】:

  • 如果您有自定义键盘,这很正常,您应该创建一个变量来跟踪和减去以获得正确的高度来移动您的视图
  • @Tj3n 什么是自定义键盘?我使用默认的模拟器设置,只是尝试删除除English (U.S.) 之外的所有键盘语言,但结果不会改变。
  • 似乎在模拟器中有所不同?你可以用真机试试看,肯定和下面的答案是一样的结果

标签: ios swift xcode keyboard ios11


【解决方案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

【讨论】:

  • 这适用于苹果键盘,而上述行为适用于自定义键盘。由于这个原因,我不得不更新我的应用程序。
  • 我猜除了code还有别的,谢谢确认。
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2019-01-10
  • 2021-07-10
  • 2018-03-26
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多