keyboardWillShow 开火两次

keyboardWillShow fire twice

我遇到了问题 "keyboardWillShow" 触发了两次,但是 "keyboardWillHide" 调用了一次。

这里是 an example,我在 "keyboardWillShow" 触发后立即打印键盘尺寸。 我还在 "viewDidLoad" 中放置了断点,观察者只注册了一次。 我添加了两个元素 "UITextField" 和 "UITextView",两者的行为相同。

我正在使用 iOS 9.2,swift 语言,xcode 7

低于我的ViewController

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        print("keyboardWillShow sizes: \(keyboardSize)")
    }

}

func keyboardWillHide(notification: NSNotification) {
    print("HideHideHide")
}

}

更新

第一次触发一次尺寸: keyboardWillShow 尺寸:(0.0, 568.0, 320.0, 253.0)

其余的两次,大小不同:(第二个 y 位置改变了,高度也改变了) keyboardWillShow 尺寸:(0.0, 568.0, 320.0, 216.0) keyboardWillShow 尺寸:(0.0, 352.0, 320.0, 216.0)

可能您订阅了多个 UIKeyboardWillShowNotification 而忘记取消订阅了。

尝试在 viewWillAppear 中添加观察者并在 viewWillDisappear 中移除观察者。

您是只输入这个 ViewController 还是浏览几个 ViewControllers?现在我看不到任何取消订阅通知的代码,这意味着一旦你再次输入 ViewController 它将再次订阅(假设它的 viewDidLoad 方法再次运行)。奇怪的是,其中只有一个发射了两次。好的做法是以各自相反的方法订阅和取消订阅。如果您在 ViewDidLoad 中订阅,则在 deinit 中取消订阅。如果您在 viewWillAppear 订阅,在 viewWillDisappear

取消订阅
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

检查以便在离开 ViewController 时运行 deinit。

问题与模拟器有关 在真实设备上,它会按预期触发一次。

我删除所有添加的键盘,只保留系统的,然后该方法将只触发一个 time.If 添加一个新键盘,该方法仍然触发两次。也许这是一个系统错误。 System Keyboard

是否正在设置文本输入特征 - 键盘类型?

示例: 如果您将键盘类型设置为 "Number Pad",理想情况下它应该调用一次,但它被调用了两次。请检查并确定。

解决方法:你可以维护一个bool来检查键盘是否已经启动,并在执行选择器代码块时检查它的值。