我将如何将KeyboardWillShowNotification中的缓动动画应用于SwiftUI的.animation修改器?

时间:2020-01-15 23:22:25

标签: swift core-animation swiftui uiviewanimation

在我的SwiftUI布局中,当键盘可见时,它将文本字段和按钮移动到键盘上方,因此不会阻塞任何内容。效果很好,但是我目前无法像在持续时间内那样将缓动应用于动画。

这是我的观点

struct ContentView: View {
    @State private var name = ""

    @ObservedObject private var keyboard = KeyboardResponder()

    var body: some View {
        VStack(spacing: 0) {
            TextField("Fill in the restaurant name", text: $name)
              .padding(.all)
            TextField("Fill in the restaurant name", text: $name)
              .padding(.all)
        }
        .padding(.bottom, keyboard.currentHeight)
        .animation(.easeOut(duration: keyboard.duration)) //trying to apply the easing I grabbed from my keyboard ObservableObject here
    }
}

这是我用来在需要时为视图设置动画的键盘响应器

final class KeyboardResponder: ObservableObject {
    private var notificationCenter: NotificationCenter
    @Published private(set) var currentHeight: CGFloat = 0

    var duration: TimeInterval = 0
    var curve: Int = 0

    init(center: NotificationCenter = .default) {
        notificationCenter = center
        notificationCenter.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    deinit {
        notificationCenter.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {

        duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        curve =  notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int //how can I add this to my animation modifier

        print("~~~~> curve \(curve)")

        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            currentHeight = keyboardSize.height
        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        curve =  notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int
        currentHeight = 0
    }
}

在keyBoardWillShow通知中,我可以抓取缓动,但是从那里我无法弄清楚如何将其应用于视图中的.animation修改器。持续时间很容易申请。也许我需要制作自己的动画类型?我什至不确定这是否可能。

.animation(.easeOut(duration: keyboard.duration))

在UIKit中,UIView.animate中有一个options参数,您可以在其中应用缓动。

UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(curve))], animations: {
      self.view.layoutIfNeeded()
    }, completion: nil)```

0 个答案:

没有答案