Layout Anchors, NSLayoutConstraint and Visual Format Language?
The gist
All three approaches create the same NSLayoutConstraint objects; only the API differs.
- Layout Anchors (
NSLayoutAnchor, iOS 9+) — the recommended way:view.leadingAnchor.constraint(equalTo:constant:). Type-safe (you cannot tieleadingAnchortotopAnchor— the compiler refuses to mix axes), concise, works withUILayoutGuide(safeAreaLayoutGuide,layoutMarginsGuide,keyboardLayoutGuide). NSLayoutConstraint(item:attribute:relatedBy:toItem:attribute:multiplier:constant:)— the low-level initializer. Verbose, and mistakes (a wrong attribute) only show up at runtime. Needed when attributes are chosen dynamically.- Visual Format Language (VFL) — an ASCII-art-style string DSL:
"H:|-16-[title]-8-[value(>=80)]-16-|". It creates a whole row of constraints at once, but is not type-safe, does not covermultiplier,centerX/YorsafeArea, and string errors crash at runtime. Effectively legacy: new code does not use it, and Swift projects replace it withUIStackViewand anchors.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep