如何依次为视图设置动画

How to animate views in turn

我想动画化屏幕上视图的到达,依次一个接一个。现在我的应用程序绘制了圆圈,它们同时到达了屏幕。但我希望第一个圆圈能占据它的位置,只有在这之后第二个圆圈才会开始它的动画等等。这个问题有什么解决方案?

import SwiftUI

struct ContentView: View {
    var body: some View {
        GenrealView()
    }
}

struct GenrealView: View {
    @State var hide = false
    
    var body: some View {
        giveViewForBody()
    }
    
    func giveViewForBody() -> some View {
        ZStack {
            drawCircles()
            Button(action: {
                self.hide.toggle()
            }) {
                Text(hide ? "Show circles" : "Hide circles")
            }.padding(50)
        }
    }
    
    func drawCircles(times: Int = 4) -> some View {
        ForEach(0..<times) { _ in
            Circle()
                .fill(Color.green)
                .frame(width: 100, height: 100)
                .position(x: -100, y: -100)
                .offset(x: CGFloat(hide ? 0 : 100 + Int.random(in: 100...300)),
                        y: CGFloat(hide ? 0 : 200 + Int.random(in: 50...600)))
                .animation(.easeIn(duration: 2.0))
        }
    }
}

为每个Circle()添加一个.delay,并使每个连续的延迟更大。将 index in 添加到 ForEach 循环中,然后进行延迟 .delay(2.0 * Double(index)):

func drawCircles(times: Int = 4) -> some View {
    ForEach(0..<times) { index in
        Circle()
            .fill(Color.green)
            .frame(width: 100, height: 100)
            .position(x: -100, y: -100)
            .offset(x: CGFloat(hide ? 0 : 100 + Int.random(in: 100...300)),
                    y: CGFloat(hide ? 0 : 200 + Int.random(in: 50...600)))
            .animation(Animation.easeIn(duration: 2.0).delay(2.0 * Double(index)))
    }
}