Search code examples
iosswiftautolayoutnslayoutconstraintuiviewanimation

Why do these constraints seem to lag when animated?


I am animating my constraints using UIView.animate. drawerHeight is a constraint variable.

Here is the code:

drawerHeight?.constant = newHeight

UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.65, initialSpringVelocity: 2, options: .allowUserInteraction, animations: {
    self.superview?.layoutIfNeeded()
})

Here is a video of what the issue looks like.

Looking at the bottom of the video, the bottom edge appears to lag behind. Why do these constraints seem to lag when animated?

This is a self-answered question. This post is to help people in the future discover what they did wrong, and how to quickly fix it.


Solution

  • The issue was that the constraint was attached to a view in a deeper hierarchy than before. When using layoutIfNeeded(), it should be called on the superview of the view containing the constraints.

    In my situation, I put the view with the drawerHeight constraint within another UIView, which made it deeper in the hierarchy.

    I fixed the issue by doing

    self.superview?.superview?.layoutIfNeeded() ,

    instead of

    self.superview?.layoutIfNeeded() .