如果屏幕旋转,则UIKeyboardWillShowNotification调用两次

时间:2016-02-01 17:10:16

标签: ios swift swift2 nsnotificationcenter

键盘出现时会创建通知并消失。

override func viewDidLoad() {

    super.viewDidLoad()

    // Creates notification when keyboard appears and disappears
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

}

override func viewWillDisappear(animated: Bool) {

    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)

}

func keyboardWillShow(notification: NSNotification) {

    self.adjustingHeight(true, notification: notification)

}

func keyboardWillHide(notification: NSNotification) {

    self.adjustingHeight(false, notification: notification)

}

private func adjustingHeight(show: Bool, notification: NSNotification) {

    // Gets notification information in an dictionary
    var userInfo = notification.userInfo!
    // From information dictionary gets keyboard’s size
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
    // Gets the time required for keyboard pop up animation
    let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
    // Animation moving constraint at same speed of moving keyboard & change bottom constraint accordingly.
    if !(show && self.bottomConstraint.constant != self.bottomConstraintConstantDefault) {
        if show {
            self.bottomConstraint.constant = (CGRectGetHeight(keyboardFrame) + self.bottomConstraintConstantDefault / 2)
        } else {
            self.bottomConstraint.constant = self.bottomConstraintConstantDefault
        }
        UIView.animateWithDuration(animationDurarion) {
            self.view.layoutIfNeeded()
        }
    }

    self.hideLogoIfSmall()

}

当键盘已经显示并且我旋转屏幕时会发生奇怪的行为。然后发生下一个动作:

  1. UIKeyboardWillHideNotification名为
  2. 调用UIKeyboardWillShowNotification(使用键盘的旧高度)
  3. 调用UIKeyboardWillShowNotification(使用键盘的新高度)
  4. 结果是我的视图没有正确更新,因为第一次调用UIKeyboardWillShowNotification时我得到的键盘高度不同于第二次。

1 个答案:

答案 0 :(得分:-2)

最后我找到了解决方案。当我得到keyboardFrame时,我正在使用UIKeyboardFrameBeginUserInfoKey,它在动画开始之前返回键盘的框架。正确的方法是使用UIKeyboardFrameEndUserInfoKey,它在动画完成后返回键盘的框架。

let keyboardFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

现在UIKeyboardWillShowNotification被调用两次,但在两次调用中返回相同的键盘高度。