Reputation: 29
I currently have a static background colour:
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
How would I code to create a series of animated colours over a set number of seconds (for example 5 seconds per colour) and then return to the beginning of the colour loop?
I've tried the following...
self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
UIView.animate(withDuration: 5.0, animations: { () -> Void in
self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0);
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
})
...but this just stays on the last blue colour.
Upvotes: 1
Views: 1868
Reputation: 21
you can try this:
let maxNumberOfRepeats = 10
var currentNumberOfRepeats = 0
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in
currentNumberOfRepeats = currentNumberOfRepeats + 1
if currentNumberOfRepeats == maxNumberOfRepeats {
timer.invalidate()
UIView.animate(withDuration: 1, animations: {
self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0) //return to first color
})
} else {
UIView.animate(withDuration: 1, animations: {
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) //or any other random color
})
}
}
Upvotes: 0
Reputation: 2353
You must make a nested animation
self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
UIView.animate(withDuration: 5.0, animations: { () -> Void in
self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0);
},
completion: { finished in
UIView.animate(withDuration: 5.0, animations: { () -> Void in
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
}, completion: { finished in
//other color do the same
})
})
Upvotes: 2