可以为CALayer的Alpha设置动画,但不能设置backgroundColor的动画

Sim*_*lGy 6 cabasicanimation swift

我想为图层的背景色设置动画。我可以为Alpha设置动画,但不能为背景颜色设置动画。

作品:

var animation = CABasicAnimation(keyPath: "opacity")
animation.toValue = 0.6
animation.duration = 0.1
customCALayer.addAnimation(animation, forKey: nil)
Run Code Online (Sandbox Code Playgroud)

不起作用(无动画,无错误):

var animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = UIColor.redColor().CGColor
animation.toValue   = UIColor.whiteColor().CGColor
animation.duration = 0.1
customCALayer.addAnimation(animation, forKey: nil)
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?backgroundColor 是可动画的属性

我已经阅读了几篇关于此的文章,但不了解我所缺少的内容。对于noop动画缺乏反馈很具挑战性,我不确定这是哪里出了问题。我已经尝试过将转换为AnyObjectNSValue用作包装器,但没有得到任何帮助。

相关答案(对我不起作用):

cle*_*ens 1

你的动画基本上是正确的,即使 Swift 版本同时已经过时。在当前版本中,它看起来像这样:

let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = UIColor.red.cgColor
animation.toValue   = UIColor.white.cgColor
animation.duration = 0.1
customCALayer.add(animation, forKey: nil)
Run Code Online (Sandbox Code Playgroud)

如果图层的背景颜色不是白色,则动画结束后图层将恢复为原始颜色。可以通过做一些小的改变来避免这种情况:

customCALayer.backgroundColor = UIColor.white.cgColor // This step isn't necessary if the Layer is white already.
let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = UIColor.red.cgColor
animation.duration = 0.1
customCALayer.add(animation, forKey: nil)
Run Code Online (Sandbox Code Playgroud)

动画将颜色从红色更改为白色,动画结束后图层仍保持白色。

在许多情况下,隐式动画足以满足这种情况:

CATransaction.begin()
CATransaction.setAnimationDuration(0.1)
customCALayer.backgroundColor = UIColor.white.cgColor
CATransaction.commit()
Run Code Online (Sandbox Code Playgroud)

使用隐式动画,您还可以轻松创建多个并行动画。例如背景颜色和不透明度:

CATransaction.begin()
CATransaction.setAnimationDuration(0.1)
customCALayer.backgroundColor = UIColor.white.cgColor
customCALayer.opacity = 0.0
CATransaction.commit()
Run Code Online (Sandbox Code Playgroud)