0

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

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))
        }
    }
}
4

1 回答 1

0

.delay为每个添加一个Circle(),并使每个连续的延迟更大。添加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)))
    }
}
于 2020-10-19T13:17:39.863 回答