SeanRobinson159 SeanRobinson159 - 2 months ago 269
Swift Question

Animation bug in iOS 10

Since iOS 10 I have noticed animating a layout change (

layoutIfNeeded()
) isn't animating. Here is my UIView extension that works great on iOS 9 and below.

func slideIn(from edgeConstraint: NSLayoutConstraint, withDuration duration: Double = 0.25, finishedAnimating: (() -> Void)? = nil) {
dispatch_async(dispatch_get_main_queue()) {
edgeConstraint.constant = 0
UIView.animateWithDuration(duration,
delay: 0.0,
options: .BeginFromCurrentState,
animations: { self.layoutIfNeeded() },
completion: { didComplete in
finishedAnimating?()
})
}
}

func slideOut(from edgeConstraint: NSLayoutConstraint, withDuration duration: Double = 0.25, finishedAnimating: (() -> Void)? = nil) {
dispatch_async(dispatch_get_main_queue()) {
edgeConstraint.constant = -self.frame.height
UIView.animateWithDuration(duration,
delay: 0.0,
options: .BeginFromCurrentState,
animations: { self.layoutIfNeeded() },
completion: { didComplete in
finishedAnimating?()
})
}
}


Does anyone know why it isn't animating?

Answer

In your animation blocks you're calling self.layoutIfNeeded() where self is the instance of UIView that you want to animate. Calling layoutIfNeeded() redraws the view that the method is called upon and all if it's subviews. In your case, you don't want to redraw the UIView, you want to redraw the view's superview.

Your functions would make sense and work properly if they were called in a view controller but since they are called in an extension on the UIView itself, you need to call something like view.superview?.layoutIfNeeded()