带有动画完成回调的 SwiftUI

Kri*_*lci 23 animation ios swift ios13 swiftui

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

withAnimation(.linear(duration: 0.1)) {
    self.someState = newState
}
Run Code Online (Sandbox Code Playgroud)

当上述动画完成时是否有任何回调被触发?

如果有关于如何在 SwiftUI 中使用完成块完成动画而不是 的任何建议withAnimation,我也愿意接受这些建议。

我想知道动画何时完成,以便我可以做其他事情,就本示例而言,我只想在动画完成时打印到控制台。

paw*_*222 28

不幸的是,这个问题还没有好的解决方案。

但是,如果您可以指定 的持续时间Animation,则可以DispatchQueue.main.asyncAfter在动画完成时触发操作:

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

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    print("Animation finished")
}
Run Code Online (Sandbox Code Playgroud)


Sh_*_*han 15

现在从Xcode 15.0 beta 开始我们有一个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")
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)


Cen*_*ion 14

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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()
    }
}
Run Code Online (Sandbox Code Playgroud)


Saú*_*ril 7

您需要使用自定义修饰符。

我已经做了一个示例,使用完成块对 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)
  }
}

Run Code Online (Sandbox Code Playgroud)


dev*_*jac 6

在这个博客上,Guy Javier 描述了如何使用 GeometryEffect 来获得动画反馈,在他的示例中,他检测动画何时达到 50%,因此他可以翻转视图并使视图看起来像有 2 个边

这是完整文章的链接,里面有很多解释:https : //swiftui-lab.com/swiftui-animations-part2/

我将在这里复制相关的片段,这样即使链接不再有效,答案仍然是相关的:

在这个例子中,@Binding var flipped: Bool当角度在 90 度和 270 度之间时为真,然后为假。

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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