ios SwiftUI with Animation completion回调

ds97pgxw  于 2023-06-07  发布在  iOS
关注(0)|答案(6)|浏览(270)

我有一个基于状态的swiftUI动画:

withAnimation(.linear(duration: 0.1)) {
    self.someState = newState
}

当上述动画完成时,是否会触发任何回调?
如果有任何关于如何在SwiftUI中使用非withAnimation的完成块来完成动画的建议,我也愿意接受。
我想知道动画什么时候完成,这样我就可以做其他的事情,对于这个例子,我只想在动画完成时打印到控制台。

ego6inou

ego6inou1#

不幸的是,这个问题还没有好的解决方案。
但是,如果可以指定Animation的持续时间,则可以使用DispatchQueue.main.asyncAfter在动画结束时触发动作:

withAnimation(.linear(duration: 0.1)) {
    self.someState = newState
}

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    print("Animation finished")
}
bnlyeluc

bnlyeluc2#

这里有一个简化和通用的版本,可以用于任何单值动画。这是基于我在等待苹果提供更方便的方法时在互联网上找到的一些其他例子:

struct AnimatableModifierDouble: AnimatableModifier {

    var targetValue: Double

    // SwiftUI gradually varies it from old value to the new value
    var animatableData: Double {
        didSet {
            checkIfFinished()
        }
    }

    var completion: () -> ()

    // Re-created every time the control argument changes
    init(bindedValue: Double, completion: @escaping () -> ()) {
        self.completion = completion

        // Set animatableData to the new value. But SwiftUI again directly
        // and gradually varies the value while the body
        // is being called to animate. Following line serves the purpose of
        // associating the extenal argument with the animatableData.
        self.animatableData = bindedValue
        targetValue = bindedValue
    }

    func checkIfFinished() -> () {
        //print("Current value: \(animatableData)")
        if (animatableData == targetValue) {
            //if animatableData.isEqual(to: targetValue) {
            DispatchQueue.main.async {
                self.completion()
            }
        }
    }

    // Called after each gradual change in animatableData to allow the
    // modifier to animate
    func body(content: Content) -> some View {
        // content is the view on which .modifier is applied
        content
        // We don't want the system also to
        // implicitly animate default system animatons it each time we set it. It will also cancel
        // out other implicit animations now present on the content.
            .animation(nil)
    }
}

这里有一个关于如何将其与文本不透明度动画一起使用的示例:

import SwiftUI

struct ContentView: View {

    // Need to create state property
    @State var textOpacity: Double = 0.0

    var body: some View {
        VStack {
            Text("Hello world!")
                .font(.largeTitle)

                 // Pass generic animatable modifier for animating double values
                .modifier(AnimatableModifierDouble(bindedValue: textOpacity) {

                    // Finished, hurray!
                    print("finished")

                    // Reset opacity so that you could tap the button and animate again
                    self.textOpacity = 0.0

                }).opacity(textOpacity) // bind text opacity to your state property

            Button(action: {
                withAnimation(.easeInOut(duration: 1.0)) {
                    self.textOpacity = 1.0 // Change your state property and trigger animation to start
                }
            }) {
                Text("Animate")
            }
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
iovurdzv

iovurdzv3#

在这个博客上,Guy Javier描述了如何使用GeometryEffect来获得动画反馈,在他的示例中,他检测到动画何时达到50%,因此他可以翻转视图并使其看起来像是有2个边
这里是全文的链接,有很多解释:https://swiftui-lab.com/swiftui-animations-part2/
我将在这里复制相关的片段,这样即使链接不再有效,答案仍然是相关的:
在本例中,当Angular 在90 °和270 °之间时,@Binding var flipped: Bool变为true,然后变为false。

struct FlipEffect: GeometryEffect {

    var animatableData: Double {
        get { angle }
        set { angle = newValue }
    }

    @Binding var flipped: Bool
    var angle: Double
    let axis: (x: CGFloat, y: CGFloat)

    func effectValue(size: CGSize) -> ProjectionTransform {

        // We schedule the change to be done after the view has finished drawing,
        // otherwise, we would receive a runtime error, indicating we are changing
        // the state while the view is being drawn.
        DispatchQueue.main.async {
            self.flipped = self.angle >= 90 && self.angle < 270
        }

        let a = CGFloat(Angle(degrees: angle).radians)

        var transform3d = CATransform3DIdentity;
        transform3d.m34 = -1/max(size.width, size.height)

        transform3d = CATransform3DRotate(transform3d, a, axis.x, axis.y, 0)
        transform3d = CATransform3DTranslate(transform3d, -size.width/2.0, -size.height/2.0, 0)

        let affineTransform = ProjectionTransform(CGAffineTransform(translationX: size.width/2.0, y: size.height / 2.0))

        return ProjectionTransform(transform3d).concatenating(affineTransform)
    }
}

您应该能够将动画更改为您想要实现的任何内容,然后在完成后获取绑定以更改父对象的状态。

bejyjqdl

bejyjqdl4#

您需要使用自定义修改器。
我已经做了一个例子,动画的偏移量在X轴与完成块。

struct OffsetXEffectModifier: AnimatableModifier {

    var initialOffsetX: CGFloat
    var offsetX: CGFloat
    var onCompletion: (() -> Void)?

    init(offsetX: CGFloat, onCompletion: (() -> Void)? = nil) {
        self.initialOffsetX = offsetX
        self.offsetX = offsetX
        self.onCompletion = onCompletion
    }

    var animatableData: CGFloat {
        get { offsetX }
        set {
            offsetX = newValue
            checkIfFinished()
        }
    }

    func checkIfFinished() -> () {
        if let onCompletion = onCompletion, offsetX == initialOffsetX {
            DispatchQueue.main.async {
                onCompletion()
            }
        }
    }

    func body(content: Content) -> some View {
        content.offset(x: offsetX)
    }
}

struct OffsetXEffectModifier_Previews: PreviewProvider {
  static var previews: some View {
    ZStack {
      Text("Hello")
      .modifier(
        OffsetXEffectModifier(offsetX: 10, onCompletion: {
            print("Completed")
        })
      )
    }
    .frame(width: 100, height: 100, alignment: .bottomLeading)
    .previewLayout(.sizeThatFits)
  }
}
nhaq1z21

nhaq1z215#

你可以试试VDAnimation library

Animate(animationStore) {
    self.someState =~ newState
}
.duration(0.1)
.curve(.linear)
.start {
    ...
}
tyu7yeag

tyu7yeag6#

现在从Xcode 15.0beta开始,我们有一个completion回调

struct MainView: View {
    @State private var animate = false
    
    var body: some View {
        Text("Hello with xcode 15")
            .scaleEffect(value ? 2 : 1)
            .onTapGesture {
                withAnimation {
                    value.toggle()
                } completion: {
                    // To do
                    print("Animation have finished")
                }
            }
    }
}

相关问题