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



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

   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("nnn(keyboardSize.height)nn")
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }
@objc func keyboardWillBeHidden(_ notification: NSNotification) {
        self.view.frame.origin.y = 0
    }

第一次调用它时,它会打印 258.0,并且视图向上移动。后续调用将打印 216.0。键盘每次向上移动相同的量。第一次将视图移动正确的量(视图底部正好在键盘上方(,随后底部 (42px( 位于键盘后面。

知道是什么原因造成的吗?

代替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)
    }

相关内容

  • 没有找到相关文章

最新更新