首页 > 解决方案 > 在敲击键盘键后触发keyboardDidShowNotification 和keyboardWillShowNotification

问题描述

这是整个应用程序的代码。只需UITextField在情节提要上添加一个并点击它。您将打印“AAAA”。然后点击键盘上的任意键。它将再次打印“AAAA”。

为什么在这种情况下会第二次触发 UIResponder.keyboardDidShowNotification 通知?我怎样才能防止这种情况?

keyboardWillShowNotification 的行为相同 :(

代码:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        addKeyboardObservers(to: .default)
    }

    func addKeyboardObservers(to notificationCenter: NotificationCenter) {
          notificationCenter.addObserver(
              forName: UIResponder.keyboardDidShowNotification,
              object: nil,
              queue: OperationQueue.main,
              using: { _ in
                    print("AAAA")
              }
          )
    }
}

Harish 的代码也一样:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
          self,
          selector: #selector(keyboardWasShown),
          name: UIWindow.keyboardDidShowNotification,
          object: nil)
    }

    @objc func keyboardWasShown(_ notification: NSNotification) {
        print("AAA")
    }

}

标签: iosswiftiphonenotificationcenter

解决方案


为什么不在下面使用?

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(keyboardWasShown),
      name: UIWindow.keyboardDidShowNotification,
      object: nil)
  }

  @objc func keyboardWasShown(_ notification: NSNotification) {

  }
}

推荐阅读