'Color cycle not cycling through all colors in swift
Solution 1:[1]
The animation block in UIView.animate(...) does not generate a sequence of animations.
So, the code as you're written it does not go from color 0 to 1 to 2 etc.
Instead, you'll want to use Keyframe animation.
Here's a simple example of a view that cycles continuously through the colors array:
class ColorCycleView: UIView {
var colors: [UIColor] = [
.purple, .blue, .green, .yellow, .orange
]
override func didMoveToSuperview() {
startAnim()
}
func startAnim() {
// total duration is number of colors (so, 1-second per color change)
// if we want 2-seconds per color change, for example, use TimeInterval(colors.count * 2)
let totalDuration: TimeInterval = TimeInterval(colors.count)
// relative duration is a percentage of the whole
// so with 5 colors, for example, it will be 0.2
let relDuration: CGFloat = 1.0 / CGFloat(colors.count)
// we want each change to start in sequence, so
// we'll increment this in our loop below
// for example, with 5 colors, the relative start times will be:
// 0.0, 0.2, 0.4, 0.6, 0.8
var relStartTime: TimeInterval = 0.0
UIView.animateKeyframes(withDuration: totalDuration, delay: 0.0, options: [.repeat, .autoreverse, .calculationModeCubicPaced], animations: {
self.colors.forEach { c in
UIView.addKeyframe(withRelativeStartTime: relStartTime, relativeDuration: relDuration, animations: {
self.backgroundColor = c
})
relStartTime += relDuration
}
})
}
}
Note that you also don't want to execute this code in layoutSubviews() ... that can be (and very often is) called multiple times.
Either call a "start animating" func from the controller, or trigger it automatically from somewhere like didMoveToSuperview() as shown above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DonMag |

