Question 4
How Auto Layout works
At a high level, how does Auto Layout work? What are the major gotchas?
Answer outline
Auto Layout lets you describe relationships between views: edges, spacing, and sizes. On each layout pass the engine solves those linear constraints and assigns a frame to every view.
Many controls (UILabel, UIImageView, buttons) report an intrinsic content size, a preferred width and height, so they size themselves without every dimension hardcoded. Priorities decide what yields when space is tight or spare. Content hugging resists growing beyond the intrinsic size, and compression resistance resists shrinking below it.
Three gotchas cause most of the pain:
- 1.Conflicts: constraints that cannot all be true, such as duplicate required pins, or
translatesAutoresizingMaskIntoConstraintsleft on while you also add constraints. The engine breaks one of them and logs the whole set. - 2.Ambiguity: too few constraints, or a view with no intrinsic size, so more than one layout satisfies them. The result looks right on one device and wrong on another.
- 3.Churn:
layoutIfNeeded()called everywhere instead of fixing the constraints, or anupdateConstraintsoverride that loops. Patching frames by hand on rotation or a keyboard change causes the same repeated passes, so pin to the safe area and keyboard layout guides.
Stack views handle rows and columns for you, but each child still needs enough information to size and position itself predictably.
Principles
- Every layout is relationships plus intrinsic size plus priorities, and each view needs enough constraints to be unambiguous.
- Unsatisfiable and ambiguous are different errors with different fixes: remove or relax constraints for the first, add them for the second.
- Whichever view has the lowest compression resistance shrinks first, and whichever has the lowest hugging grows first.
- Leave
translatesAutoresizingMaskIntoConstraintson and you get a second, conflicting set of constraints for free.
Follow-up angles
- Self-sizing cells need a full vertical constraint chain on the
contentView, from top edge to bottom edge, so Auto Layout can compute the height.



