How to animate with Auto Layout

suggest change

Without 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:

  1. Change the constant of the constraint, then call layoutIfNeeded inside the animation block so the frames interpolate. A timer or CADisplayLink is 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)
  1. Change the constraints, then call layoutIfNeeded inside 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];
}];
  1. Change the priority of the constraints. This is less CPU intensive than adding and removing constraints.
  2. Remove all constraints and use autoresizing masks. For the latter, set view.translatesAutoresizingMaskIntoConstraints = YES.
  3. Use constraints that don’t interfere with the intended animation.
  4. 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.
  5. 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];
  1. Override layoutSubviews. Call [super layoutSubviews] and fine-tune the frames.
  2. Change the frame in viewDidLayoutSubviews. Auto Layout is applied in layoutSubviews, so change the frame afterward in viewDidLayoutSubviews. Setting a frame that invalidates layout can loop.
  3. Opt out of Auto Layout and set frames manually. Override layoutSubviews and do not call super. layout is 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents