DEV Community

Midhet Sulemani
Midhet Sulemani

Posted on

Core Animations in Swift

Apple's documentation says that: Core Animation provides high frame rates and smooth animations without burdening the CPU and slowing down your app. Most of the work required to draw each frame of an animation is done for you. You configure animation parameters such as the start and end points, and Core Animation does the rest, handing off most of the work to dedicated graphics hardware, to accelerate rendering.

The main difference between UIView animations and Core Animations is that UIView animations animate the whole view whereas Core Animations have the ability to animate each sublayer of the UIView.

You can find all the various types of animations enabled by Core Animation in iOS here.


Let's continue with adding a Core Animation to the TODO Application we built in the previous post of this series, or you can find the starter project here.


We are going to build a live color changing gradient animation to the Add ToDo button.

Gradient animation preview

Let's create a method called animateGradient() in NewTodoViewController.swift.

Add the following code in the method:

func animateGradient() {
    // cycle through all the colors, feel free to add more to the set
    if currentGradient < gradientSet.count - 1 {
        currentGradient += 1
    } else {
        currentGradient = 0
    }

    // animate over 3 seconds
    let gradientChangeAnimation = CABasicAnimation(keyPath: "colors")
    gradientChangeAnimation.duration = 3.0
    gradientChangeAnimation.toValue = gradientSet[currentGradient]
    gradientChangeAnimation.fillMode = CAMediaTimingFillMode.forwards
    gradientChangeAnimation.isRemovedOnCompletion = false
    gradientChangeAnimation.delegate = self
    gradient.add(gradientChangeAnimation, forKey: "gradientChangeAnimation")
}
Enter fullscreen mode Exit fullscreen mode

And now you have created your first Core Animation!

Core Animation is a very powerful library and you can do almost all the animations your heart desires. So get a move on and explore the full potential of Core Animations!

That's it for this series on animations and stay tuned for more tips and tricks in iOS :)

That's a wrap

Latest comments (0)