3
votes

I've read many questions that state in order to animate constraint changes, we just need to...

self.someConstraint.constant = 0.f;
[UIView animateWithDuration:0.5f animations:^{
    [self layoutIfNeeded];
}];

Recently, I've read that custom view subclasses should use the -(void)updateConstraints method on a UIView to perform constraint updates in case there are many property changes that occur that would cause you to do the above code block in multiple places, which would lead to many layout passes that are unneeded.

UIView -(void)updateConstraints documentation

I actually like this approach where we update all constraints. Some simple code of...

- (void)updateConstraints
{
    if(someCondition)
    {
         self.someConstraint.constant = 0.f;
    }
    //Maybe some other conditions or constant changes go 
    here based on the current state of your view.
    [super updateConstraints];
}

At this point, my original constraint animation code now only becomes

[self setNeedsUpdateConstraints];

The only problem with this is I've now lost the ability to animate these changes.
I've looked over the view documentation to find a way to animate these changes to the constraints, but I can't seem to find an appropriate method to override to call [self layoutIfNeeded] in an animation block. Even in this case, I feel it should be unnecessary to call that because a layout is going to be performed, and I feel I shouldn't have to force it right then and there.

Does anyone know HOW to cause these constraint changes to animate?

1

1 Answers

2
votes

You need to call [self updateConstraintsIfNeeded]. So your code would look like this...

[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.25 animations:^{
    [self layoutIfNeeded];
}];