旋转后接收两个不同高度的键盘

ang*_*dev 2 nsnotificationcenter ios swift swift2

我有一个视图,当键盘出现时调整约束.所以当键盘出现并消失时我会收到通知.

键盘已经显示并旋转屏幕时会出现上述行为.然后发生下一个动作:

  1. UIKeyboardWillHideNotification调用
  2. 调用UIKeyboardWillShowNotification(使用键盘的旧高度)
  3. 调用UIKeyboardWillShowNotification(使用键盘的新高度)

因此,updateView函数接收第一个高度,然后接收不同的高度.这导致视图的奇怪移动调整值的两倍.

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)

}

deinit {

    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 = (CGRectGetHeight(keyboardFrame) + self.bottomConstraintConstantDefault / 2)
    } else {
        self.bottomConstraint.constant = self.bottomConstraintConstantDefault
    }
    UIView.animateWithDuration(animationDurarion) {
        self.view.layoutIfNeeded()
    }

    self.hideLogoIfSmall()

}
Run Code Online (Sandbox Code Playgroud)

ang*_*dev 7

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

let keyboardFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
Run Code Online (Sandbox Code Playgroud)