iOS Dev Nugget 167 Animation with Auto Layout


Need to run a code review on your codebase? Hire me

Cocoa Touch makes it very easy to perform simple animations. e.g. this will move a UIView instance right.

CGRect rect = aView.frame;
rect.origin.x += 20;
[UIView animateWithDuration:0.3 animations:^{
    aView.frame = rect;

With Auto Layout, if you keep in mind that Auto Layout works by letting developers define a set of constraints to calculate layout and with the system computing the actual layout frames for you using -layoutSubviews and related methods like -layoutIfNeeded, then animation with Auto Layout is simple to understand too:

someConstraint.constant = toValue;
[UIView animateWithDuration:0.3 animations:^{
    [aView.superview layoutIfNeeded];

To get the equivalent of changing the frame(s) in aView.frame = rect in the first snippet, you get Cocoa Touch to do a layout pass for you using the updated constraints by calling -layoutIfNeeded within the animation block. One inconvenience is you need to keep the constraint you want to modify around. A few other important points:

  1. You are not restricted to modifying constraint constants. You can add/remove constraints for more elaborate animation.
  2. In the first snippet you assign the updated CGRect to the frame of the view (aView) you want to modify, but in the second snippet, using Auto Layout, you'll usually want to call -layoutIfNeeded on the parent of the view. This is because the parent may use updated constraints which affect the layout of other children.
  3. If you want to start the animation from another state, you should update your constraints to reflect that and call -layoutIfNeeded immediately before snippet two, so by the time the -animateWithDuration:animations: block runs the layout has already been updated to that initial state correctly.

PS: I wrote some code, pull some data from the iOS app store and wrote a post about iOS app icon colors. You might find it interesting: iOS App Icon Colors in the Year 2015. Let me know what you think.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues