How to animate with Auto Layout
suggest changeWithout Auto Layout, animation is accomplished by changing a view’s frame over time. With Auto Layout, the constraints dictate the view frame, so you have to animate the constraints instead. This indirection makes animation harder to visualize.
Here are the ways to animate with Auto Layout:
- Change the constant of the constraint, then call
layoutIfNeededinside the animation block so the frames interpolate. A timer orCADisplayLinkis a different technique. This example is one animation:
Objective-C:
self.someConstraint.constant = 10.0;
[UIView animateWithDuration:0.25 animations:^{
[self.view layoutIfNeeded];
}];
Swift:
self.someConstraint.constant = 10.0
UIView.animate(withDuration: 0.25, animations: self.view.layoutIfNeeded)
- Change the constraints, then call
layoutIfNeededinside an animation block. The block interpolates the frames that result from those constraints. The snippet below does not change a constraint, so nothing moves unless one already changed.
[UIView animateWithDuration:0.5 animations:^{
[view layoutIfNeeded];
}];
- Change the priority of the constraints. This is less CPU intensive than adding and removing constraints.
- Remove all constraints and use autoresizing masks. For the latter, set
view.translatesAutoresizingMaskIntoConstraints = YES. - Use constraints that don’t interfere with the intended animation.
- Use a container view. Position the superview using constraints. Then add a subview with constraints that don’t fight the animation, for example a center relative to the superview. This moves some of the constraints to the superview, so they don’t fight the animation in the subview.
- Animate layers instead of views. A layer transform does not change Auto Layout constraints.
CABasicAnimation* ba = [CABasicAnimation animationWithKeyPath:@"transform"];
ba.autoreverses = YES;
ba.duration = 0.3;
ba.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)];
[v.layer addAnimation:ba forKey:nil];
- Override layoutSubviews. Call
[super layoutSubviews]and fine-tune the frames. - Change the frame in viewDidLayoutSubviews. Auto Layout is applied in
layoutSubviews, so change the frame afterward inviewDidLayoutSubviews. Setting a frame that invalidates layout can loop. - Opt out of Auto Layout and set frames manually. Override
layoutSubviewsand do not callsuper.layoutis the AppKit method, not the UIKit one.
Quick tip: if the parent of the animated view is not being interpolated (that is, the animation jumps from beginning to end state), call layoutIfNeeded() in the deepest view that is the parent of the view that is animated (in other words, that is not affected by the animation). I don’t know exactly why this works.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents