Swift 3 UIView animation

Alex Brown picture Alex Brown · Sep 14, 2016 · Viewed 42.1k times · Source

Since upgrading my project to swift 3 my autolayout constraint animations aren't working; to be more specific, they're snapping to the new position rather than animating.

UIView.animate(withDuration: 0.1,
               delay: 0.1,
               options: UIViewAnimationOptions.curveEaseIn,
               animations: { () -> Void in
                   constraint.constant = ButtonAnimationValues.YPosition.DefaultOut()
                   self.layoutIfNeeded()
    }, completion: { (finished) -> Void in
    // ....
})

I know they added the UIViewPropertyAnimator class but am yet to try it.

Answer

Enoch Ng picture Enoch Ng · Sep 20, 2016

I had this problem too with the newest update to swift 3.

To be exact, whenever you want to animate the view, you actually call layoutIfNeeded on the superview of that view.

Try this instead:

UIView.animate(withDuration: 0.1,
           delay: 0.1,
           options: UIViewAnimationOptions.curveEaseIn,
           animations: { () -> Void in
               constraint.constant = ButtonAnimationValues.YPosition.DefaultOut()
               self.superview?.layoutIfNeeded()
}, completion: { (finished) -> Void in
// ....
})

It seems in the past they've been lenient about being able to just relayout the view you want to animate. But its in the documentation that you should really be calling layoutIfNeeded in the superview.