UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Animating based on values in an Array?

Forums > SwiftUI

Hey everyone,

I'm trying to create a traffic light where based on the values inside of an array the lights would animate accordingly with a delay. However, it seems that as I loop through an array and try to animate the state, the state only gets changed at the every end when the for loops is done.

Here's an example of my animation code:

for state in stateMachine.state_array {
                sleep(1)
                switch state {
                case MachineState.go:
                    self.isRedOn.toggle()
                    self.isGreenOn.toggle()
                    print(state)
                case MachineState.slow_down:
                    self.isGreenOn.toggle()
                    self.isYellowOn.toggle()
                    print(state)
                case MachineState.stop:
                    self.isGreenOn.toggle()
                    self.isYellowOn.toggle()
                    print(state)
                }

 }

Here's how I set the values for the colors:

 ZStack {
            RoundedRectangle(cornerRadius: 8.0, style: .continuous)
                .frame(width: 80, height: 200)
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(isRedOn ? .red : Color.red.opacity(0.4))
                .offset(y: -40)
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(isYellowOn ? .yellow: Color.yellow.opacity(0.4))
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(isGreenOn ? .green : Color.green.opacity(0.4))
                .offset(y: 40)
            RoundedRectangle(cornerRadius: 8.0, style: .continuous)
                .frame(width: 20, height: 240)
                .offset(y: 200)
 }

The view only animates only once on the first state, even though inside the loop I can see each state being printed with a delay. Any ideas on how I would go about fixing this? Should I be using a DispatchQueue or possibliy even Combine?

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.