Blog

Animating Views

Graphics, iOS Development, UI

Motivation

In nearly all of my iOS projects I am required to subclass UIView and override the drawRect method with custom drawing. Now in order to animate new properties on this view I can not use the standard UIView animation methods that we usually have for animating views.

Instead, I was creating a display link for every view and setting up animation methods to allow the property to be animated as required. This was leading to a lot of the same code written multiple times for each custom view. So I needed a general solution where I could subclass the view and animate custom properties when and how I choose.

Ideas

  • Use CALayer and take advantage of the needsDisplayForKey and actionForKey class methods to implement animation on custom properties.
  • Create a subclass of UIView that can have animations added to the view which it will then perform at a given time set by the parameters of the animation.

Solution

Using the CALayer approach it would reduce the code required to set up display links to create the animation on the property, however it would mean updating the class functions for every CALayer subclass.

The approach of using a UIView subclass would allow me to add animation on a property at any given time without having to declare it as a property that should update the display (if I choose not to). By using the Objective-C method valueForKey I am able to get and set any property of the class but it does restrict me to working with Objective-C valid properties (and classes). However, the vast majority of time this is likely anyway.

Bonuses

In the process of creating my own set of animations I realised that I could use this as a chance to add all of the animation curves that we would likely want to use. This is something that you don't get from the animations offered by UIView. So we are able to use the following animation curves at will:

  • Spring based (critical and underdamped with user defined parameters)
  • Quadratic (ease-in, ease-out & ease-in-out)
  • Cubic (ease-in, ease-out & ease-in-out)
  • Quartic (ease-in, ease-out & ease-in-out)
  • Quintic (ease-in, ease-out & ease-in-out)
  • Sinusoidal (ease-in, ease-out & ease-in-out)
  • Exponential (ease-in, ease-out & ease-in-out)
  • Circular (ease-in, ease-out & ease-in-out)

Animate With Me

You can use this RCAnimatableView class in your own projects. I have created a playground file which contains all the necessary code in the Sources directory.

Playground File
Get your project started

Talk to us today about web and app projects