UIKeyboardDidShowNotification 被调用了两次

UIKeyboardDidShowNotification is called twice

在我的 UIViewController 中,底部有两个 UITextField。所以在键盘上出现我正在尝试移动到上面。下面是我处理键盘的代码

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShown:", name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHidden:", name: UIKeyboardDidHideNotification, object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidHideNotification, object: nil)
}

//    MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
    if let initialFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        let convertedFrame = self.view.convertRect(initialFrame, fromView: nil)

        iY = viewLogin.frame.origin.y

        var currentFrame = viewLogin.frame
        currentFrame.origin.y = convertedFrame.origin.y - 140
        self.viewLogin.frame = currentFrame
        UIView.animateWithDuration(0.2, animations: { () -> Void in

        })
    }
}


func keyboardHidden(notification: NSNotification){
    var currentFrame = viewLogin.frame
    currentFrame.origin.y = iY
    UIView.animateWithDuration(0.2, animations: { () -> Void in
        self.viewLogin.frame = currentFrame
    })
}

第一个 UITextField 工作正常。但是,当我尝试移动到第二个 UITextField 时,再次调用 keyboardShown() 并且我的视图移回底部。我无法检测到实际原因。如果我遗漏了什么,请告诉我。

提前致谢

问题与自动布局有关。我解决如下

//    MARK: - Handling Notification
func keyboardShown(notification: NSNotification){
    self.bottomConstraint.constant += 125
    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.viewLogin.layoutIfNeeded()
    })
}


func keyboardHidden(notification: NSNotification){
    self.bottomConstraint.constant -= 125
    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.viewLogin.layoutIfNeeded()
    })
}

如果我们使用了 AutoLayout,我们需要更改 属性 约束。