键盘加载完成后视图移动,如何让视图同时移动

The view shifts after the keyboard is finished loading, how to I get the view to shift at the same time

当我调用键盘时,它会向上滑动到位,然后视图的其余部分会向上滑动以为它腾出空间。同样,当我关闭键盘时,键盘将滑出,然后视图的其余部分将向下滑动。是否可以让键盘和视图同时滑动?

这是我目前拥有的代码

// MARK: Animated Keyboard
@objc func keyboardWillShow(notification: NSNotification) {

    // check to see if a keyboard exists
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        print("Show")

        // Check to see if the information for the size of the keyboard exists
        guard let userInfo = notification.userInfo
            else {return}

        // get the size of the keyboard
        guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
            else {return}

        // get the duration of the keyboard transition
        let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double

        // get the type and speed of the keyboard transition
        let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt

        // move the frame by the size of the keyboard
        let keyboardFrame = keyboardSize.cgRectValue
        UIView.animateKeyframes(withDuration: duration, delay: -0.2, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
            if self.view.frame.origin.y == 0 {
                self.view.frame.origin.y -= keyboardFrame.height
            }
        }, completion: nil)


    }
}   

这不会导致任何错误,编译和运行没有问题。看起来很糟糕。

从您的描述来看,您实际上注册的是 keyboardDidShowNotification 而不是 keyboardWillShowNotification

确保您注册了正确的通知。

您还应该使用 UIView.animate 方法而不是 UIView.animateKeyframes。这当然也意味着您需要将 UIView.KeyframeAnimationOptions 替换为 UIView.AnimationOptions.

最后,不要尝试使用负延迟。 UIKit 有很多功能,但时间旅行不是其中之一。