简体   繁体   中英

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()
}

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM