UIKit Animations Are Messy — Here’s Why SwiftUI Can Fix That

5 min read#Swift#iOS#SwiftUI

Photo by Ricardo Viana on Unsplash.

Not only do iOS animations feel and look great, but they are also very easy to create. So how do I have the nerve to say that they are “messy”?

To understand that, let’s go back to the early days of iOS development — when we wrote code in Objective C and Xcode was an IDE with multiple windows and no tabs (really, Xcode 3 was garbage) — and try to learn what has happened since then in UIKit.


Do You Remember commitAnimations?

Some of UIView’s properties are animated — background color, frames, center, and more.

To animate a view, all you had to do was modify its properties and wrap it with beginAnimations and commitAnimations functions:

UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.2)
view.frame = newFrame
UIView.commitAnimations()

In the example above, the view frame is being animated to newFrame.

You can’t get any simpler than that, can you?

The main problem with this example is that it is difficult to sync this animation with the rest of the screen flow. We had to use a delegate function to take action when the animation ends (speaking of ancient history, no blocks or closures).

In other words, developers needed a completion block to chain animations together or better control animation events.

Fortunately, in iOS 4, Apple gave us a new feature called UIView block-based animations.


UIView Block-Based Animations

With UIView block-based animations, it is very easy to set up animations, chain them, or sync them with the rest of the UI flow:

UIView.animate(withDuration: 0.2) {
 	self.view.frame = newFrame
 } completion: { finished in
    self.doSomethingAtTheEnd()
}

Now, isn’t that lovely?

Later, Apple added Key-Frame animations to help us create even more sophisticated animations in our apps.

But then Apple introduced Auto-Layout.


Auto-Layout

In iOS 6, Apple added Auto-Layout, and block-based animations became a little bit trickier.

In Auto-Layout, we don’t change the view frame but rather change one (or more) of its Auto-Layout constraints. The Auto-Layout system handles the frame changes based on a set of other constraints being prioritized.

Take a look at the following code snippet:

UIView.animate(withDuration: 0.2) {
   self.leadingConstraint.constant = 50
}

Unlike in the previous example with frame changes, running this example won’t provide any animations. The reason for that is that changes in constraints lead to other changes in the parent view, and therefore they will be applied only in the following UI rendering cycle.

So, what is the solution? Just call layoutIfNeeded() inside the animation block:

UIView.animate(withDuration: 0.2) {
    self.leadingConstraint.constant = 50
    self.layoutIfNeeded()
}

Simple, right? Not so fast. Which view needs to refresh its layout? The animated view or its parent?

Since the animated view influences its siblings, we need to re-lay out the parent view.

Auto-Layout is a system of constraints, and a change in one constraint may affect multiple views. Therefore, we need to take into account that changes in a parent constraint may have side effects. Errggg!


Core Animation Layers and Auto-Layout

But it doesn’t end there.

Each UIView is based on a CALayer (stands for Core Animation Layer).

There’s a main layer for each UIView, and we can add sub-layers to the main layer (just like the subviews mechanism).

Core Animation Layers allow us to add shapes, gradients, shadows, and more effects to our views.

The main CALayer bounds are always equal to its UIView bounds. But the sub-layers’ frames are static, and we need to update them constantly to keep them synced with our UIView.

One way to do that is to override the layoutSubviews() method called by the system in every UI refresh cycle (if needed).

override func layoutSubviews() {
    super.layoutSubviews()
    sublayer.frame = self.bounds
}

So, on the one hand, we call layoutIfNeeded() inside the animation block. On the other hand, we update the CALayer frame in layoutSubviews().

It feels a little awkward, but it should work, no?

Well, it doesn’t.

It seems that Core Animation Layers and Auto-Layout don’t work together nicely. Auto-Layout is relevant to UIViews only.

If we want to add a unique layer to our user interface, it is better to create a UIView based on that layer and add it to the view hierarchy.

In other words, forget about a hierarchy of CALayers being transitioned nicely. Create a dedicated UIView and connect it to the Auto-Layout system.


Why Do We Need Animations?

At this point, we should already understand that something is not working correctly with UIKit animations. Auto-Layout doesn’t fit in nicely, and the CALayer issues cause us headaches.

So, we need to ask ourselves: What is the purpose of animations anyway?

After all, it’s not like we are running a Pixar or Disney studio.

Animations are not there only to look nice. They also provide a great way to reflect UI state changes to the user.

In fact, most animations do just that — express to the user what has changed on the screen.

If a new screen pops from the bottom, there should be a reason for that. Transitions between screens give the user context for where they came from and where they are supposed to return.

SwiftUI, as a declarative framework, deals with state changes naturally and takes care of responding to data updates, button pressing, and more.

Once we wrap these state changes with animation, we practically solve most of the pitfalls I just mentioned about UIKit.

It seems that declarative frameworks such as SwiftUI go hand in hand with animations and can be implemented quickly.


And If I Don’t Use SwiftUI?

Even though UIKit is not a declarative framework, we can borrow some principles or ideas from SwiftUI.

We can create our own state using our view model and “refresh” the screen every time the state is updated.

That means there would be one place and one place only where all the constraints or displayed data are being modified.

Once we wrap the “refresh” code with the animation block, we may get a user experience similar to the one that exists in SwiftUI — a direct match between the UI and the state, animated nicely.


Summary

I know that animations in UIKit seem very convenient for some developers and are probably considered the best thing that has happened to humanity since Oreo ice cream.

Personally, I find it very messy and not in sync with other iOS libraries such as Auto-Layout or Core Graphics.

I think that SwiftUI solves most of these issues, and even if it does not, it can teach us how to handle it better in our current UIKit code base.


Originally published on Medium.

Be the first to like it

Comments

Leave a comment

Comments appear after they're approved.

All posts