How Auto Layout works

UIKit Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

The console says 'Unable to simultaneously satisfy constraints' and lists NSAutoresizingMaskLayoutConstraint. Fix?

Options
Hint 1 of 1

Where does NSAutoresizingMaskLayoutConstraint come from?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Set translatesAutoresizingMaskIntoConstraints = false on the view before activating its constraints

Correct. Otherwise UIKit adds constraints from the frame that fight yours.

Why not the others?
  • B Lower your constraints' priority to 999. That hides the conflict, and the frame-based constraints win.
  • C Call layoutIfNeeded() after activating. It only runs layout sooner; the conflict remains.
  • D Set the frame manually as well. Mixing frames and constraints is the cause, not the fix.

30-second answer

Auto Layout turns constraints into linear equations and solves them with an incremental solver (based on Cassowary), honouring priorities: required constraints must hold, and lower priorities are satisfied as closely as possible. Conflicts happen when required constraints contradict each other. A common cause is forgetting translatesAutoresizingMaskIntoConstraints = false, which adds hidden constraints from the frame.

Practise saying it · 45 s. No recording, just a timer

Explain how Auto Layout resolves constraints.

Say your answer out loud, then check which of these points you covered:

  • Linear equations and priorities
  • Conflict vs ambiguity
  • translatesAutoresizingMaskIntoConstraints

Deep dive

Layout runs in passes: update constraints, then layout, then display.

Ambiguity means too few constraints; a conflict means contradictory ones.

Use constraint identifiers and the View Debugger to find the culprit.

Batch changes with NSLayoutConstraint.activate.

Common mistakes

  • Lowering priorities to 999 to hide a real conflict.
  • Calling layoutIfNeeded everywhere.

Senior take & follow-ups

Seniors explain priorities, the solver and how they debug conflicts.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you find an ambiguous layout?

    Show hint

    The View Debugger, or hasAmbiguousLayout in the debugger.

  2. What does layoutIfNeeded do?

    Show hint

    Forces a layout pass now, for example inside an animation block.

From the author

Catalog - UI

Made by the author: browse UIKit components with live demos, and copy their code snippets into your project.

Suggest a fix if something here is wrong or out of date.