Search code examples
swiftcakeyframeanimation

How to use CAKeyframeAnimation?


I'm studying animation and I want to use CAKeyframeAnimation. On Apple Developer I found the following code snippet:

let colorKeyframeAnimation = CAKeyframeAnimation(keyPath: "backgroundColor")

colorKeyframeAnimation.values = [
    UIColor.red.cgColor,
    UIColor.green.cgColor,
    UIColor.blue.cgColor
]
colorKeyframeAnimation.keyTimes = [0, 0.5, 1]
colorKeyframeAnimation.duration = 2

But I have not found solution about how to add this animation object to view. How to make it work and apply to anything?


Solution

  • You add it to the view’s layer with add(_:forKey:).


    Alternatively, if you don't want to animate with CoreAnimation, you can use the UIView.animateKeyframes API, e.g.:

    // if the animatedView isn't already .red, set it as such
    //
    // animatedView.backgroundColor = .red
    
    // then start your animation from the current color, to green, to blue
    
    UIView.animateKeyframes(withDuration: 2, delay: 0, options: [], animations: { 
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: { 
            self.animatedView.backgroundColor = .green
        })
        UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: { 
            self.animatedView.backgroundColor = .blue
        })
    }, completion: nil)
    

    Note, the "relative" start time and duration values are a percentage of the overall animation duration.