UIView Animation with Swift

Here is a very simple way to do UIView Animations in Swift.

First, you create an IBOutlet for a constraint created in Interface Builder in Xcode – in my case, I had a constraint that anchored to the bottom of the containing view. In the code example, the constraint is named “constraintToAnimate”. You just control drag from the Storyboard to your code as you would when connecting a control, but in this case you connect a constraint. It will look something like this (the name of your constraint will hopefully be different):

    @IBOutlet weak var constraintToAnimate: NSLayoutConstraint!

The following snippet is basically a straight-up conversion of Apple’s own Objective-C example given in the¬†documentation article¬†Auto Layout by Example in the Animating Changes Made by Auto Layout section (you may need to scroll down to find that section).

    UIView.animateWithDuration(0.3, animations: {
        // make constraint changes here...
        self.constraintToAnimate.constant = 250 // your value here.
        }, completion: {
            (value: Bool) in
            // completion code here...

Basically, in pre-Auto Layout days you would just animate the frame. Today you just animate the constraint. It works great and once you get your head wrapped around it, it’s pretty straightforward.