Animating CALayer background color and update model value

强颜欢笑 提交于 2019-12-12 16:11:22

问题


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

回答1:


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

}


来源:https://stackoverflow.com/questions/29064668/animating-calayer-background-color-and-update-model-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!