swift / iOS - 键盘高度值在通知之间变化,但实际高度保持不变

时间:2018-03-23 02:23:16

标签: ios swift

我有一个视图,我正试图在键盘出现/消失时移动。这是基本代码。

   func registerForKeyboardNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: .UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: .UIKeyboardDidHide, object: nil)
    }

    @objc func keyboardWasShown(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0 {
                print("\n\n\n\(keyboardSize.height)\n\n")
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }

@objc func keyboardWillBeHidden(_ notification: NSNotification) {
        self.view.frame.origin.y = 0
    }

第一次调用时,它打印258.0,视图向上移动。后续调用打印216.0。键盘每次都向上移动相同的量。第一次将视图移动到正确的数量(视图底部位于键盘上方),后面的部分(42px)位于键盘后面。

知道可能导致这种情况的原因吗?

1 个答案:

答案 0 :(得分:0)

而不是UIKeyboardFrameBeginUserInfoKey,请使用UIKeyboardFrameEndUserInfoKey

此外,我建议您只使用一个通知来处理对帧的所有更改,如下所示:

    //Add keyboard did Layout change notification
    NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardNotification(notification:)),name:NSNotification.Name.UIKeyboardWillChangeFrame,object: nil)

然后像这样实现它

@objc func keyboardNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let endFrameY = endFrame?.origin.y ?? 0
        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
        if endFrameY >= UIScreen.main.bounds.size.height {
            //Change This
            //self.signInButtonBottomConstraint?.constant = 0.0
        } else {
            //Modify This
            //self.signInButtonBottomConstraint?.constant -= (endFrame?.size.height ?? 0.0)
        }
        UIView.animate(withDuration: duration,
                       delay: TimeInterval(0),
                       options: animationCurve,
                       animations: { self.view.layoutIfNeeded() },
                       completion: nil)
    }