DevPrep

All topics › Auto Layout

Describe the layout cycle: setNeedsLayout, layoutSubviews, updateConstraints.

Senior PRO

Three phases and their direction

The cycle runs on every run-loop pass before the frame is rendered (in the CATransaction commit), only for views marked "dirty".

  1. Update constraints — a bottom-up pass (leaves to root). updateConstraints() is called on views that received setNeedsUpdateConstraints(). This is where you batch-change or create constraints; the engine solves the system itself. Apple recommends overriding updateConstraints only for performance when there are many changes; normally you change constraints right where the event happened.
  2. Layout — a top-down pass (root to leaves). The engine solves the system and calls layoutSubviews(): the view receives its frame and positions its subviews. setNeedsLayout() marks the view for the next pass, layoutIfNeeded() performs layout immediately (this is how constraint animation works). On the controller side this is wrapped by viewWillLayoutSubviews / viewDidLayoutSubviews.
  3. Display — a top-down pass. setNeedsDisplay() marks the layer and draw(_:) / display(_:) is called. Changing frame does not redraw automatically unless contentMode is .redraw.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store