Auto Layout or Manual Layout?

I get asked this question a lot, when should you use Auto Layout? If it was a job interview at Google, the answer is no Auto Layout :).  If it’s a job interview at startups, Auto Layout is the way to go.  So when should we use Auto Layout and when should we use Manual Layout?

Modern apps need to be responsive to changes in screen sizes or the contents they are displaying and Auto Layout makes building these responsive layout a breeze.  By using Interface Builder (IB), you can specify how the size and position of your views should change when their parent views or neighboring views change.  Adopting Auto Layout requires a different mindset than the old approach of setting view frames directly.  It does require less coding. In practice, I would almost always use Auto Layout when practical.  There are cases where Auto Layout wouldn’t work such as:

  1. Animating views under Auto Layout requires animating the constraints, which can be a pain to do.
  2. Auto Layout doesn’t work well with view transforms
  3. Auto Layout can be slow.

In practice, you can mix constraint-based layout with manual-layout in the same view hierarchy.  Consider this example: one of your custom views contains several subviews, you are using Auto Layout to position all but one of them. This last subview has a scale and rotation transform applied that conflicts with the constraint-based layout, so you don’t apply any constraints to it.  You can think of Auto Layout as just an additional step that runs automatically in your view’s layoutSubviews method.  It does some magic but in the end it just laid out all the subviews correctly based on layout constraints.  What you do to your subviews’ frames after Auto Layout has done its job, doesn’t matter.

Override layoutSubviews (or viewDidLayoutSubviews if you want to do this in a view controller), call super (which performs the Auto Layout step) and then perform any manual layout we want to add.  In the end, that’s the happy medium between Auto Layout and Manual Layout.

Posted in: iOS

Leave a comment