animating positions in autolayout

Animations in Swift are pretty straight forward:

UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in                          
  self.lbl.alpha = 0.0;
}, completion: { (finished: Bool) -> Void in
   self.lbl.hidden = true
})

but if the position of an element was done by “autolayout” the order is a bit more tricky.

Step 1: you need to set up the connection in “Interface Builder” to a member like this:

@IBOutlet var topConstraint:NSLayoutConstraint!;

Step 2: the animation:

// recommended, although probably not neccesary
self.view.layoutIfNeeded() 

self.topConstraint.constant = -30.0;
UIView.animateWithDuration(annitime, delay: 0.1, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
self.view.layoutIfNeeded()
                    }, completion: { (finished: Bool) -> Void in
                        
                })

valid as of Swift 2.1, found here

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.