Animation and Autolayout

The interplay between animation and autolayout can be tricky (see Chapter 14). An animation may appear to work perfectly, but there can be a hidden trap waiting to be sprung. The reason is that animation and layout are two different things. As part of an animation, you may well be directly changing a view’s frame (or bounds, or center). You’re really not supposed to do that to position a view when you’re using autolayout; but no penalty is incurred, because no layout has happened. However, it is entirely possible that layout will happen. And at that moment, what’s going to matter, as we know very well, are the constraints. If the constraints that the system finds in place don’t resolve to the size and position that a view has at that moment, the view will jump as the constraints are obeyed. This is almost certainly not what you want.

To persuade yourself that this can be a problem, just animate a view and then ask for immediate layout by calling layoutIfNeeded, like this:

CGPoint p = v.center;
p.x += 100;
[UIView animateWithDuration:1 animations:^{
    v.center = p;
} completion:^(BOOL b){
    [v layoutIfNeeded]; // prove that we are in trouble
}];

If we’re using autolayout, the view slides to the right and then jumps back to the left. This is bad. It’s up to us to keep the constraints synchronized with the reality, so that when layout comes along in the natural course of things, our views don’t jump into undesirable states. This is no more than a natural extension ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.