Swift – Simple Animations

Need to create simple animation? Use UIView.animateWithDuration() or one of the other similar methods. While this is fairly easy to use, it is bit cumbersome. Why not make a helper method to simplify your work?

  1. Imagine a method that takes a UIView as a an argument. Since all UI elements are sub classes of UIView you can pass any UI element.
  2. For convenience imagine all of the elements were created at the location where they will end their motion. This means our method will offset the element in the x and or y, then move it back to it’s starting point.
  3. To make the motion interesting and give us some controller we need to pass in the duration.
  4. If everything is moving at the same time things are dull, and some things are not possible. We need a delay.

Our method looks like this:

func animateThing(thing: UIView, offsetY: CGFloat, offsetX: CGFloat, time: NSTimeInterval, delay: NSTimeInterval) {
// some code here 
}

The parameters are

  • thing – a UIView or subclass of UIView, which is the thing to animate
  • offsetY – CGFloat the amount to offset in the y axis. This sets the starting point on the y axis, thing will move back to original position!
  • offsetX – CGFloat the amount to offset on the x axis.
  • time – NSTimeInterval, this can be a Double (0.5 for example), it sets the length of the animation in seconds
  • delay – NSTimeInterval, this sets the time to wait before beginning the motion.

A few points

  1. The offsetX, and offsetY can use positive or negative numbers. Negative values move the object left or up. Positive numbers move down, or right. These determine an offset, that places the object at a new position before the motion begins, the object will end its motion at it’s starting point.
  2. Time is set in seconds. Delay determines how long to wait before the motion begins. The total time of the animation will be time + delay.
  3. It’s probably best to call this function in viewWillAppear. This way the objects get positioned before we see the view, and the motion will be applied each time the view is shown.

Using an Extension

An extension allows you to add functions to existing classes. Rather than adding this function to each custom view controller we create, using an extension we can add an extension to the UIViewController class, and all ViewControllers will have the new function.

Add the first code example to your project in a file named extensions.swift. You’re done! The second code example shows some usage examples and is not required.