Reputation: 951
I am building Simon Says app using SwiftUI, and as I was building it I encountered a bug. The problem is with one specific function that I typed below. This function sets alphas of the Simon Says buttons (just a simple animation of pressing button) and sets them back to 0.5. I want this to run one at the time on each of the Views because so far the animation runs on all of the buttons at the same time.
All help will be appreciated!
for index in settings.guessArray {
wait(time: 2.0) {
settings.alphas[index] = 1.0
wait(time: 0.3) {
settings.alphas[index] = 0.5
}
}
}
Upvotes: 2
Views: 106
Reputation: 154583
Maybe something like this would work...
The waits execute asynchronously, so increase the initial wait time for each button to space them out in time:
var offset = 0.0
for index in settings.guessArray {
wait(time: 2.0 + offset) {
settings.alphas[index] = 1.0
wait(time: 0.3) {
settings.alphas[index] = 0.5
}
}
// increase this value to increase the spacing between the buttons
// lighting up
offset += 0.3
}
//if you're using this function on multiple SwiftUI views at the same time
//consider placing the offset variable in @EnvironmentObject.
Upvotes: 1
Reputation: 93161
I'm flying blind here but what you achieve that with a semaphore. Adapt from the code below:
let semaphore = DispatchSemaphore(value: 0)
for index in settings.guessArray {
semaphore.wait() // When animation on one button begins
wait(time: 2.0) {
settings.alphas[index] = 1.0
wait(time: 0.3) {
settings.alphas[index] = 0.5
semaphore.signal() // When animation on a button finishes
}
}
}
Upvotes: 0