tezvyn:

How does Auto Layout resolve constraints?

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

understanding constraint-based layout.

OUTLINE

Auto Layout solves a system of prioritized linear equations; intrinsicContentSize is a view's natural size; hugging resists growing, compression resistance resists shrinking.

WHAT THIS TESTS This verifies that you understand Auto Layout as a linear constraint solver and that you can reason about ambiguous or conflicting layouts using priorities rather than guessing. It separates engineers who fight the layout engine from those who direct it.

A GOOD ANSWER COVERS Auto Layout expresses each constraint as a linear equation or inequality of the form attribute equals multiplier times another attribute plus a constant, each carrying a priority from 1 to 1000. The engine, built on a Cassowary-style solver, finds values for every view's frame that satisfy all required constraints, which have priority 1000, and best satisfies optional ones, breaking lower-priority constraints when the system is overdetermined. intrinsicContentSize is the size a view naturally wants given its content, such as a label sized to its text or a button sized to its title, so you need not pin both width and height explicitly. When a view could be larger or smaller than its intrinsic size, two priorities arbitrate. Content hugging priority resists growing beyond the intrinsic size, pulling edges inward. Compression resistance priority resists shrinking below it, pushing back against clipping.

COMMON WRONG ANSWERS Swapping the definitions, saying hugging prevents shrinking. Believing all constraints are absolute and conflicts crash. Ignoring that priorities decide which view stretches or truncates.

LIKELY FOLLOW-UPS What happens when two required constraints conflict? Which view stretches when two labels share a row? How do you debug an ambiguous layout? What priority value is required versus optional?

ONE CONCRETE EXAMPLE Two labels sit side by side in a fixed-width row. To make the second label truncate while the first shows fully, raise the first label's compression resistance above the second's. To decide which label hugs its text and which expands to fill slack, lower the hugging priority of the one that should stretch, so the solver enlarges it while the other stays at intrinsic width.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.