How to animate views in turn

55 views Asked by At

I want to animate the arriving of views on the screen, in turn, one by one. Now my application draws circles and they arrive on the screen at the same time. But I would like it if the first circle will take its position and only after this the second circle will start its animation and etc. What solutions does this problem have?

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

There are 1 answers

0
vacawama On BEST ANSWER

Add a .delay to each Circle() and make the delay larger for each successive one. Add index in to your ForEach loop and then make the delay .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)))
    }
}