0

I have an extension of UILabel with a shake method. This method shakes the label for 2 seconds. It works great.

I am trying to chain a 2 second red -> white text-color change to the label text. It does not work great.

Here's my progress.

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)

    }
}

The problem:

The colorsAnimation CABasicAnimation has no effect on the text color. The text color does not make a 2 second transition from red to white.

How can I chain the shake animation and colorsAnimation together on the label?

Joe
  • 3,772
  • 3
  • 33
  • 64

1 Answers1

0

CALayers don't have a foregroundColor property. They do have a backgroundColor property. You could animate that. (Simply change the line let colorsAnimation = CABasicAnimation(keyPath: "foregroundColor") to let colorsAnimation = CABasicAnimation(keyPath: "backgroundColor")

Why are you using CAAnimation rather than UIView animation? CAAnimation can do things that UIView animation cannot, but it is a lot harder to use and not as well documented.

(There is a keyframe UIView animation, for example.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272