Elementary Layer Animations

Today I learned that apart from UIView animations provided by UIKit, we can also use Layer Animations integrated inside any ViewController. Layer animation is also faster in performance because it is relatively “lower-level”.

For an animation, if we use UIView, the code would be like:

UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: {
    // something about UI change
}, completion: nil)

One little problem with this method is that we have to specify the UI modification in the animation closure. If we have ten different views we would like to animate, we would have to cut and paste this chunk for at least ten times. Obviously we would like to reuse code, so layer animation is the way to go:

animationName = CABasicAnimation(keyPath:"some property")
animationName.fromValue = 0.0
animationName.toValue = 1.0
animationName.duration = 5.0
object.layer.addAnimation(animationName, forKey: “key”)
animationName.setValue(object.layer, forKey: “layer”)

The above code does the same thing, but notice that it does not specify the target layer. We could simply modify fromValue or toValue and add it to another layer and it would work.

This is not all. If we set the delegate of a layer animation object to self (every NSObject already implements the delegate methods) and overrides these two functions:

func animationDidStart(anim: CAAnimation )
func animationDidStop(anim: CAAnimation , finished flag: Bool )

We would be able to monitor the status of layer animations. Neat.

Elsewhere in the class, we could use the keys that we set earlier to get either the animation object or the layer. I’ll save the code here.

Now that we have fromValue, toValue and duration, we would also like to set the delay time of our animations. Again, this is pretty easy:

animationName.beginTime = CACurrentMediaTime() + 1.0

Note that the beginTime is relative to the fixed currentMediaTime(), not that the animation is delayed by the time after the former animation.

Animations can also be grouped together with CAAnimationGroup:

let group = CAAnimationGroup()
group.animations = [animation1, animation2, animation3]

Then it is convenient to set the common properties of animations to the group.

That’s pretty much it.

Leave a Reply

Your email address will not be published. Required fields are marked *