The animation of a UIView should start right after the view is added to the superview:
class myView: UIView {
override func didMoveToSuperview() {
super.didMoveToSuperview()
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveLinear,
animations: {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
self.layer.colors = [color1, color2]
CATransaction.commit()
},
completion: nil
)
}
}
However, the result is that the animation is already over when the view becomes visible in the superview. UIView.animate does not animate but sets self.layer.colors immediately, maybe because the view is not yet visible when didMoveToSuperview is called.
How can I make the animation start normally?
Animating gradients using core animation can be done by creating a
CABasicAnimationand adding it to yourCAGradientLayer. You don't need to wrap this in aUIViewanimation block and you can do this fromviewDidMoveToSuperviewprovided that you add yourUIViewsubclass instance to the view hierarchy sometime after your root view has been added to aUIWindow. For example, in a playground one can write:and see a 20 second animation from vertical orange to blue gradient animate to a vertical red to green gradient.