Constraints and anchors
A constraint is a rule like “the label’s leading edge is 16 points from the safe area’s leading edge” or “the button’s top is 8 points below the label’s bottom”. Auto Layout solves all the rules together and sets every view’s frame.
For each view, the constraints must answer four questions: where horizontally, where vertically, how wide, how tall. Some views answer the size questions themselves: a UILabel, UIButton or UIImageView has an intrinsic content size, the size of its text or image, so you often only need to position it.
Laying out a view in code always takes three steps:
addSubview(label)label.translatesAutoresizingMaskIntoConstraints = false(otherwise UIKit adds its own constraints from the frame, and they conflict with yours)NSLayoutConstraint.activate([...])with your rules, built from anchors:leadingAnchor,trailingAnchor,topAnchor,bottomAnchor,widthAnchor,heightAnchor,centerXAnchor,centerYAnchor.
Pin content to view.safeAreaLayoutGuide, so it stays clear of the notch, the Dynamic Island and the home indicator, and use leading/trailing rather than left/right, so the layout flips automatically for right-to-left languages like Arabic and Hebrew.
Each constraint is a linear equation, item1.attribute = multiplier × item2.attribute + constant, with a relation (=, ≤, ≥) and a priority. The engine (an incremental Cassowary solver) finds frames satisfying all required constraints while minimizing violations of optional ones. Two failure modes: unsatisfiable (required constraints contradict; UIKit logs the set and breaks one, which one is unspecified) and ambiguous (several solutions; views jump between them or collapse to zero). Debug with constraint identifiers (they appear in logs), the view debugger’s purple warnings, view.hasAmbiguousLayout and exerciseAmbiguityInLayout(), and po view.value(forKey: "_autolayoutTrace") in lldb. Layout guides: safeAreaLayoutGuide, layoutMarginsGuide (respecting directionalLayoutMargins and system minimums), readableContentGuide for comfortable line lengths on iPad, and your own UILayoutGuides instead of invisible spacer views. Activate in batches with NSLayoutConstraint.activate, don’t recreate constraints on every layout pass, and remember that translatesAutoresizingMaskIntoConstraints defaults to true in code and false for views placed in Interface Builder. Views that set frame manually inside layoutSubviews are fine, and sometimes faster, for leaf-heavy custom views.
final class ProfileHeaderView: UIView {
private let avatar = UIImageView()
private let nameLabel = UILabel()
private let followButton = UIButton(configuration: .filled())
override init(frame: CGRect) {
super.init(frame: frame)
nameLabel.font = .preferredFont(forTextStyle: .headline)
nameLabel.adjustsFontForContentSizeCategory = true // follows Dynamic Type
followButton.configuration?.title = "Follow"
for view in [avatar, nameLabel, followButton] {
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
}
let margins = layoutMarginsGuide
NSLayoutConstraint.activate([
avatar.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
avatar.topAnchor.constraint(equalTo: margins.topAnchor),
avatar.bottomAnchor.constraint(lessThanOrEqualTo: margins.bottomAnchor),
avatar.widthAnchor.constraint(equalToConstant: 56),
avatar.heightAnchor.constraint(equalTo: avatar.widthAnchor),
nameLabel.leadingAnchor.constraint(equalToSystemSpacingAfter: avatar.trailingAnchor, multiplier: 1),
nameLabel.centerYAnchor.constraint(equalTo: avatar.centerYAnchor),
followButton.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: nameLabel.trailingAnchor, multiplier: 1),
followButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
followButton.centerYAnchor.constraint(equalTo: avatar.centerYAnchor),
])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}Predict the output
A label gets only two constraints: leading and top, pinned to the safe area. Its text is 'Hello'. What size is it?
let label = UILabel()
label.text = "Hello"
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
])A UILabel has an intrinsic content size, the size of its text in its font. Auto Layout turns it into constraints (with hugging and compression-resistance priorities), so position alone is enough. A plain UIView has no intrinsic size, so the same two constraints would make its size ambiguous.
Unable to simultaneously satisfy constraints
Tap the line with the bug.
override func viewDidLoad() {
super.viewDidLoad()
let banner = UIView()
banner.backgroundColor = .systemYellow
view.addSubview(banner)
NSLayoutConstraint.activate([
banner.leadingAnchor.constraint(equalTo: view.leadingAnchor),
banner.trailingAnchor.constraint(equalTo: view.trailingAnchor),
banner.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
banner.heightAnchor.constraint(equalToConstant: 60),
])
}Hint: Views created in code have one property set to true by default.
translatesAutoresizingMaskIntoConstraints is true for views created in code. UIKit turns the banner’s frame (zero, at the origin) into constraints of its own, and those contradict yours. The console prints “Unable to simultaneously satisfy constraints” with a list including NSAutoresizingMaskLayoutConstraint, and UIKit breaks one of the constraints at random, so the banner may appear with zero height or in the wrong place.
Turn it off for every view you lay out with constraints:
let banner = UIView()
banner.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(banner)When you see NSAutoresizingMaskLayoutConstraint in a conflict log, this is almost always the cause.
Deep diveReading a constraint conflict logInterview favorite
The log lists the constraints that can’t all be true, then names the one it broke. Read it bottom-up: find the views by their addresses or, better, by the identifiers you gave them (constraint.identifier = "header.height"; views can have accessibilityIdentifiers too). Look for three usual suspects: NSAutoresizingMaskLayoutConstraint (a view with translatesAutoresizingMaskIntoConstraints still on), UIView-Encapsulated-Layout-Height/Width (the size a table cell, collection cell or stack view imposes, usually conflicting with a required height inside the cell), and two required constraints you added in different places, such as a fixed width plus leading and trailing pinned to a narrower superview.
The fix is rarely deleting one: usually one of them shouldn’t be required. Lowering an inner height constraint to priority 999 lets it give way to the cell’s encapsulated height during the first pass, and the warning disappears without changing the final layout. Add a symbolic breakpoint on UIViewAlertForUnsatisfiableConstraints to stop at the moment it happens.
- Constraints are linear equations with relations and priorities; the solver satisfies required ones and minimizes optional violations. Unsatisfiable (conflict, one gets broken) vs ambiguous (several solutions).
- Debug with identifiers, the view debugger,
hasAmbiguousLayout,_autolayoutTrace, and a breakpoint onUIViewAlertForUnsatisfiableConstraints; suspects: autoresizing-mask and encapsulated-size constraints. translatesAutoresizingMaskIntoConstraints = falsein code; safe area, layout margins, readable content guide,UILayoutGuideinstead of spacer views; leading/trailing for RTL.
Check this part
What must you set on a view created in code before adding constraints to it?
Why use leading and trailing instead of left and right?
What is the difference between an unsatisfiable and an ambiguous layout?
A conflict log mentions UIView-Encapsulated-Layout-Height. What is the usual fix?