DevPrep

All topics › Auto Layout

What is a constraint (NSLayoutConstraint)?

Junior PRO

The gist

A constraint is a single linear equation or inequality between attributes of two layout objects:

item1.attribute1 (=, ≥, ≤) multiplier × item2.attribute2 + constant

For example: button.leading = superview.leading × 1 + 16 or label.width ≤ 240. The attributes are leading, trailing, top, bottom, width, height, centerX, centerY, firstBaseline, lastBaseline and the margin variants. The second item may be absent (height = 44) or be a UILayoutGuide (safe area, margins, a custom guide).

Auto Layout gathers all active constraints into a system and solves it (the Cassowary algorithm), producing each view's frame. Inequalities are a core part of the model: "no wider than the parent", "at least 44 pt" are expressed exactly that way.

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