我有一个带有 shake 方法的 UILabel 扩展。此方法将标签摇动2秒。效果很好。
我正在尝试将 2 秒的红色 -> 白色文本颜色更改链接到标签文本。它效果不佳。
这是我的进步。
extension UILabel {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 2
animation.values = [
0.0, 0.0,
-4.0, 4.0,
-7.0, 7.0,
-10.0, 10.0,
-7.0, 7.0,
-4.0, 4.0,
0.0, 0.0,
]
animation.repeatCount = 1
layer.add(animation, forKey: nil)
let colorsAnimation = CABasicAnimation(keyPath: "foregroundColor")
colorsAnimation.fromValue = UIColor.red.cgColor
colorsAnimation.toValue = UIColor.white.cgColor
colorsAnimation.duration = 2
layer.add(colorsAnimation, forKey: nil)
}
}
问题:
colorsAnimation CABasicAnimation 对文本颜色没有影响。文本颜色不会在 2 秒内从红色过渡到白色。
如何在标签上将抖动动画和颜色动画链接在一起?
最佳答案
CALayers
没有 foregroundColor
属性。它们确实有一个 backgroundColor
属性。你可以将其动画化。 (只需将行 let colorAnimation = CABasicAnimation(keyPath: "foregroundColor")
更改为 let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
为什么使用CAAnimation
而不是UIView
动画? CAAnimation
可以做 UIView
动画不能做的事情,但它很多更难使用,而且没有很好的文档记录。
(例如,有一个关键帧 UIView 动画。)
关于swift - 对 UIView 扩展的文本颜色进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239257/