When using Auto Layout, it will be inevitable that you would also want to animate views where constraints are used. Here’s a guide on how to animate Auto Layout constraints in iOS.
First, get a reference to the layout constraint. You can do this in the storyboard, by assigning an IBOutlet property to a constraint. (Select the constraint, hold control, then drag to your .m file).
Next, on your method which will trigger the animation, update the constraints. For example:
1 |
self.trailingSpaceToViewConstraint.constant = -50; |
If other constraints will be affected because of the update to the constraint above, the following must also be called:
1 |
[viewForUpdate setNeedsUpdateConstraints]; |
Now, animate yout view by calling “layoutIfNeeded” inside your animation block.
Note that you should call the “layoutIfNeeded” method of your parent container view, not the view that will be animated. If you do otherwise, then the animation will not take effect, only the constraint will (which results to immediate update of your view’s frame).
1 2 3 4 |
[UIView animateWithDuration:0.5 animations:^{ [self.view layoutIfNeeded]; } completion:completion]; |
The “self.view” above is the main view of my UIViewController.
Done! Your view should now animate.
References:
http://stackoverflow.com/questions/12926566/are-nslayoutconstraints-animatable
http://weblog.invasivecode.com/post/42362079291/auto-layout-and-core-animation-auto-layout-was
cool! thanks a lot
Thanks Much, 🙂