Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating CALayer background color and update model value

I want to animate a backgroundColor change for a sublayer in my UIView (on tintColorDidChange).

I need to animate from the layer's current background colour to the new tint colour several times (different tint colours each time), so the model value for backgroundColor needs to be updated (I can't use removedOnCompletion = false on the animation).

Using CABasicAnimation I have the colour change animation working fine if I don't update the model value (but of course the colour resets after the animation is complete). When I try to update the model value the colour change happens immediately and the animation is lost.

I attempted to disable the implicit animation and update the model value with CATransation but the animation is still lost.

How can I update the backgroundColor model value and keep my fade animation working?

override func tintColorDidChange() {
    super.tintColorDidChange()

    let colourAnim = CABasicAnimation(keyPath: "backgroundColor")
    colourAnim.toValue = self.tintColor.CGColor
    colourAnim.duration = 1.0
    self.spinnerLayer?.addAnimation(colourAnim, forKey: "colourAnimation")

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    self.spinnerLayer?.backgroundColor = self.tintColor.CGColor
    CATransaction.commit()
}
like image 479
alexkent Avatar asked Mar 16 '23 18:03

alexkent


1 Answers

Use an explicit fromValue for the animation:

override func tintColorDidChange() {
    super.tintColorDidChange()

    let colourAnim = CABasicAnimation(keyPath: "backgroundColor")
    colourAnim.fromValue = self.spinnerLayer!.backgroundColor
    colourAnim.toValue = self.tintColor.CGColor
    colourAnim.duration = 1.0
    self.spinnerLayer?.addAnimation(colourAnim, forKey: "colourAnimation")
    self.spinnerLayer?.backgroundColor = self.tintColor.CGColor

}
like image 165
jrturton Avatar answered Apr 02 '23 12:04

jrturton