UIKit Auto Layout, stack views, guides, and priorities
Auto Layout describes relationships among views. It solves those relationships for the current container, safe areas, content sizes, and priorities.
Build a complete constraint graph
let stack = UIStackView(arrangedSubviews: [titleField, bodyView, saveButton])stack.axis = .verticalstack.spacing = 12stack.translatesAutoresizingMaskIntoConstraints = falseview.addSubview(stack)
let guide = view.safeAreaLayoutGuideNSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 16), stack.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -16), stack.topAnchor.constraint(equalTo: guide.topAnchor, constant: 16), stack.bottomAnchor.constraint(lessThanOrEqualTo: guide.bottomAnchor, constant: -16)])The safe area protects interactive content. A less-than bottom constraint allows short content without forcing an unnecessary stretch.
Let text define size
Preferred fonts and adjustsFontForContentSizeCategory let labels respond to Dynamic Type. Avoid fixed label heights. Multiline labels need numberOfLines = 0 and constraints that allow vertical growth.
Content hugging expresses resistance to growing beyond intrinsic size. Compression resistance expresses resistance to shrinking below it. Change priorities to encode a real product preference, not to silence a warning at random.
Use layout guides for regions
Safe-area, readable-content, keyboard, and custom layout guides express meaningful regions without invisible spacer views. Stack views manage common linear relationships but do not replace constraints around the stack.
Debug the broken relationship
When constraints conflict, read the logged equations, add identifiers to important constraints, inspect the view hierarchy, and find the incompatible product rules. Do not lower arbitrary priorities until the console stops.
Test narrow width, split view, rotation, long localization, right-to-left layout, and the largest text sizes. One simulator screenshot is one solved case.
Validation boundary
The constraints were not compiled or rendered. Ambiguity, conflicts, keyboard layout guide behavior, Dynamic Type, localization, and size-class adaptation remain Not verified.
Series navigation
- Previous: Part 46: UIKit views, controls, target-action, and delegation
- Next: Part 48: UIKit view-controller lifecycle and containment
- Series index: Zero to iOS Hero
References
- View layout covers stack views, constraints, anchors, and layout guides.
- UIStackView manages arranged views along an axis.
- Positioning content relative to the safe area covers safe-area guides.