敲击键盘键后会触发keyboardDidShowNotification和keyboardWillShowNotification

时间:2020-03-20 16:40:57

标签: ios swift iphone notificationcenter

这是整个应用程序的代码。只需在情节提要板上添加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")
    }

}

1 个答案:

答案 0 :(得分:0)

为什么不在下面使用?

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) {

  }
}