Describe the layout cycle: setNeedsLayout, layoutSubviews, updateConstraints.
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".
- Update constraints — a bottom-up pass (leaves to root).
updateConstraints()is called on views that receivedsetNeedsUpdateConstraints(). This is where you batch-change or create constraints; the engine solves the system itself. Apple recommends overridingupdateConstraintsonly for performance when there are many changes; normally you change constraints right where the event happened. - Layout — a top-down pass (root to leaves). The engine solves the system and calls
layoutSubviews(): the view receives itsframeand 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 byviewWillLayoutSubviews/viewDidLayoutSubviews. - Display — a top-down pass.
setNeedsDisplay()marks the layer anddraw(_:)/display(_:)is called. Changingframedoes not redraw automatically unlesscontentModeis.redraw.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep