【问题标题】:Animating the text color of a UIView extension动画 UIView 扩展的文本颜色
【发布时间】:2018-09-08 20:42:32
【问题描述】:

我有一个 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 秒内从红色变为白色。

如何在标签上将摇动动画和颜色动画链接在一起?

【问题讨论】:

    标签: swift animation cabasicanimation cakeyframeanimation


    【解决方案1】:

    CALayers 没有foregroundColor 属性。他们确实有 backgroundColor 属性。你可以把它做成动画。 (只需将行let colorsAnimation = CABasicAnimation(keyPath: "foregroundColor")更改为let colorsAnimation = CABasicAnimation(keyPath: "backgroundColor")

    为什么你使用CAAnimation 而不是UIView 动画? CAAnimation 可以做 UIView 动画不能做的事情,但它很多难以使用,并且没有很好的文档记录。

    (比如有一个关键帧的UIView动画。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2011-11-22
      • 2016-03-26
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多