Animations in Swift

Doyeon
doyeona
Published in
6 min readFeb 15, 2021

Animations can add visual cues that notify users about what’s going on in the app. In iOS, animations are used extensively to reposition views, change their size, remove them from view hierarchies, and hide them. You might use animations to convey feedback to the user or to implement interesting visual effects. -developer.apple-

In iOS, we don’t need to write any drawing code because apple provides it for us 👏🏻 What we only have to do is trigger the animation and let Core animation handle the rendering of individual frames.

3types of animation

  • UIKit
  • Core Animation
  • UIViewPropertyAnimator

When to use and what to use?

At the end of the day, all UIKit-style animations are converted to Core Animation-style animations. That is, everything is actually animated using Core Animation. -StackOverFlow-

UIKit: animations are performed using UIView objects. View supports a basic set of animations that cover many common tasks such as view transitions. It can accept events from the user like touch, click and tap and it works in the main thread.

Core Animation: Use Core animations when animating of the underlying layer’s properties. It renders, composes, and animate visual elements which provides high frame rates and smooth animations without burdening the CPU and slowing down the app.

UIViewPropertyAnimator: allows complex and dynamic animation of UIView properties.

Still confuse what to use? The below image will help you figure it out!

(left)UIKit vs (right)Core animation

💁🏻‍♀️ If your view hosts custom layer objects — that is, object without an associated view — you must use Core Animation to animate any changes to them.

UIView’s animation

With UIKit, it’s the easiest way to implement your code! Very straight forward API to use as a beginner.

  • All animations on iOS are run using Core Animation. UIKit’s block-based animation methods are simply a convenience feature
  • While UIKit and Core Animation both provide animation support, they give access to different parts of the view hierarchy.

Animatable UIView properties

frame boundscenter transform alpha backgroundColor contentStretch

class func animate(withDuration duration: TimeInterval, 
delay: TimeInterval,
options: UIView.AnimationOptions = [],
animations: @escaping () -> Void,
completion: ((Bool) -> Void)? = nil)

Animate changes to one or more views using the specified duration, delay, options, and completion handler.

duration The total duration of the animation.

delay The amount of time (sec) to wait before beginning the animations.

options A mask off options indicating how you want to perform the animations 🔴 .autoreverse .repeat .curveEaseOut .curveEaseIn and click to see more!

💡 for the transition, the option starts with trans- ex. .transitionCrossDissolve

animations A block object {} containing the changes to commit to the views.

completion A block object to be executed when the animation sequence ends.

Let’s code! So how do you make simple animation with a view? I created a label and the view in the storyboard and connected them into ViewController. missions are:

1️⃣ Change the background color of the view

2️⃣ Change the height & width of the width of the view

simple animation

When you run the code, the background color of the view will change to pink and the size of the view will get bigger. but what if you wanna do another animation right after these animations? I like to change the view’s position and the color of the view.

We can use a completion handler to give another animation right after the animation.

btw, during the animations, the touch event become disable so to make it able, you have to make allowUserInteraction = true

Okay! you got how it works right? try to change the numbers and options to get used to it. btw, have you noticed that there’s another method provided usingSpringWithDamping?

It performs a view animation using a timing curve corresponding to the motion of a physical spring .

These are the added parameters,

dampingRatio To smoothly decelerate the animation without oscillation(movement back and forth at a regular speed), use a value of 1.

velocity The initial spring velocity. A value of 1 corresponds to the total animation distance traversed in one second. (become faster when it’s closer to 0)

Coding time 🙈 🙉

I made a kinda weird animation above using .repeat, .autoreverse options so that’s how animation looks like when you use usingSpringWithDamping and you can use multiple options in an array.

Wait.. what if i have multiple code blocks(nested blocks like the code below)? is there any way to improve the code? 🤦🏻‍♀️

animateKeyframes

That’s why we use keyframe to improve thosee nasty code blocks just in one! AnimateKeyframe creates an animation block object that can be used to set up keyframe-based animations for the current view.

class func animateKeyframes(withDuration duration: TimeInterval, 
delay: TimeInterval,
options: UIView.KeyframeAnimationOptions = [],
animations: @escaping () -> Void,
completion: ((Bool) -> Void)? = nil)

animations A block object containing the changes to commit to the views. typically, you call the addkeyframe(withRelativeStartTime:relativeDuration:animations:) method.

addKeyframe: Specifies the timing and animation values for a single frame of a keyframe animation.

frameStartTime The time at which to start the specified animations. This value must be in the range 0 to 1.

frameDuration The length of time over which to animate to the specified value. This value must be in the range 0 to 1 and indicates the amount of time relative to the overall animation length.

animations A block object containing the animation you want to perform. This parameter must not be nil.

UIView.animateKeyframe(withDuration: 4, ….) means the total duration of the animation will be 4 sec

withRelativeStartTime is the starting time of the animation

relativeDuration is how long is the animation presented. if it’s 0.25, then it means quarter of the 4 which is equivalent to 1(sec)

Therefore each of the addKeyframe will present a sec, and the total duration of the animation will be 4 sec.

Animation works :

1️⃣ change the background color to .magenda

2️⃣ make the alpha to 0.5

3️⃣ change the center of the x

4️⃣ change the center of the x

This is the end of the UIView animation. I don’t actually wanna break the article about animations but since this get long and long which makes me feel tired 🤦🏻‍♀️ I will be continuing with Core animation and UIViewPropertyAnimator in next post! Thank you for reading and please let me know if there’s something I need to update for the future readers!

references are linked.

animations:

--

--

Doyeon
doyeona

Passionate iOS developer creating extraordinary apps. Innovative, elegant, and collaborative. Constantly pushing boundaries.Let's build the future together📱✨🚀