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?