In UIKit, how do you pin a view to the safe area with layout anchors, and why must translatesAutoresizingMaskIntoConstraints be set to false first?
answer
- typed edges and dimensions
- returned constraints start inactive
- one call switches on a batch
- code-made views default to true
- bars, home indicator, extra insets
basics
~20 sBuild constraints from anchors against view.safeAreaLayoutGuide and switch them on together with NSLayoutConstraint.activate(_:). A view created in code turns its autoresizing mask into constraints by default, and those fight yours, so set translatesAutoresizingMaskIntoConstraints to false.
solid answer
~50 sEvery `UIView` and `UILayoutGuide` exposes anchors such as `leadingAnchor`, `topAnchor` and `widthAnchor`, and their `constraint(equalTo:constant:)` family returns an **inactive** `NSLayoutConstraint`. Nothing changes until you activate it, and `NSLayoutConstraint.activate(_:)` switches on a whole batch, usually more efficiently than one at a time. The anchor classes are typed, so pairing a horizontal anchor with a vertical one does not compile. To keep a trip card clear of the status bar, navigation bar, tab bar and home indicator, pin it to `view.safeAreaLayoutGuide` rather than to the view's own edges. First, though, set `translatesAutoresizingMaskIntoConstraints = false` on the subview: for views created in code it defaults to `true`, UIKit then adds constraints that reproduce the frame and autoresizing mask, and yours conflict with them. Set it from the container, not on `self`, and leave it alone on views UIKit manages, such as a stack view's arranged subviews.
code
swift · 21 linesimport UIKit
final class TripViewController: UIViewController {
private let card = UIView()
override func viewDidLoad() {
super.viewDidLoad()
card.backgroundColor = .secondarySystemBackground
// Opt this subview out of autoresizing-mask constraints.
card.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(card)
let safe = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
card.leadingAnchor.constraint(equalTo: safe.leadingAnchor, constant: 16),
card.trailingAnchor.constraint(equalTo: safe.trailingAnchor, constant: -16),
card.bottomAnchor.constraint(equalTo: safe.bottomAnchor, constant: -16),
card.heightAnchor.constraint(greaterThanOrEqualToConstant: 120)
])
}
}go deeper
Recall the three steps: turn off translatesAutoresizingMaskIntoConstraints, add the subview, then activate anchor constraints against the safe area guide in one batch.
Explain why the flag defaults to true for code-made views and what the generated constraints do, and why activation needs a common ancestor.
Show the habits that prevent layout bugs in review: typed anchors, leading and trailing for right-to-left, kept references whose constant changes instead of churned constraints.
Frame the team default: anchors and one activate call per view, never the item-attribute initializer, and a review rule against touching the flag on views UIKit manages.
## What a constraint is Auto Layout positions views by solving a set of **constraints**. Each `NSLayoutConstraint` is a linear equation of the form `item1.attribute1 = multiplier × item2.attribute2 + constant`, and the relation can also be `<=` or `>=`. Apple's documentation stresses that it is an equation, not an assignment: the solver may move either side to satisfy it. Every constraint has a **priority** between 1 and 1,000; by default it is 1,000, which means **required**. A layout is valid when the constraints have exactly one solution: more than one is *ambiguous*, none is *conflicting*. ## Anchors: the way to write constraints in code The header for `NSLayoutConstraint` says that building constraints with `init(item:attribute:relatedBy:toItem:attribute:multiplier:constant:)` is not recommended; anchors, available since iOS 9, are the replacement. Each view and each `UILayoutGuide` exposes them: - **`NSLayoutXAxisAnchor`**: `leadingAnchor`, `trailingAnchor`, `leftAnchor`, `rightAnchor`, `centerXAnchor`. - **`NSLayoutYAxisAnchor`**: `topAnchor`, `bottomAnchor`, `centerYAnchor`, `firstBaselineAnchor`, `lastBaselineAnchor`. - **`NSLayoutDimension`**: `widthAnchor` and `heightAnchor`, which also accept a constant (`constraint(equalToConstant:)`) or a multiplier of another dimension. Because `NSLayoutAnchor` is generic over its axis, `card.leadingAnchor.constraint(equalTo: other.topAnchor)` is a **compile error**, which removes a whole class of runtime mistakes. Prefer `leading` and `trailing` to `left` and `right` so the layout mirrors in right-to-left languages. ## Activating constraints Every `constraint(...)` method returns an **inactive** constraint; `isActive` is `false` for a new constraint. You turn it on by setting `isActive = true` or, for a group, with `NSLayoutConstraint.activate(_:)`, which has the same effect as setting each flag and is typically more efficient. Activation adds the constraint to the closest common ancestor of its items, so both views must already be in the same hierarchy: activating a constraint whose items share no ancestor throws an exception. To change a layout later, keep a reference and change its `constant`; the header notes this performs much better than removing a constraint and adding a near-identical one. ## translatesAutoresizingMaskIntoConstraints Before Auto Layout, views were placed with frames and an `autoresizingMask`. To let both systems coexist, UIKit can turn a view's frame and mask into constraints of its own. That is what `translatesAutoresizingMaskIntoConstraints` controls: 1. It **defaults to `true`** for every view you create in code; Interface Builder sets it to `false` for views it lays out. 2. While it is `true`, the generated constraints fix the view's size and position, so any constraint you add for size or position **conflicts** with them. 3. Set it to `false` on the subview **from the containing view or view controller**; Apple's documentation says not to set it on `self` inside a custom view, because that stops the superview managing its layout. 4. Do not change it on views UIKit manages, such as a view controller's root `view`, table view cells or a stack view's arranged subviews. ## The safe area layout guide `safeAreaLayoutGuide` (iOS 11) is a `UILayoutGuide` that marks the part of a view not covered by navigation bars, tab bars, toolbars and other ancestor content. For a view controller's root view it also accounts for the status bar and any `additionalSafeAreaInsets` the controller sets. When the view is not yet on screen, the guide's edges equal the view's edges, and they update once it appears, so constraints made in `viewDidLoad()` are still right. | Guide | What it marks | |---|---| | `safeAreaLayoutGuide` | the area free of bars and other covering content | | `layoutMarginsGuide` | the view's margins, measured from the safe area by default (`insetsLayoutMarginsFromSafeArea`) | | `readableContentGuide` | a centred width that is comfortable for reading text | | `keyboardLayoutGuide` | the space the keyboard occupies (iOS 15) | ## Mistakes that show up in review - **The flag left at `true`.** The console then reports a conflict that includes constraints UIKit generated from the frame, and the view can stay where its frame put it. - **Too many required constraints on one axis.** Pinning top and bottom *and* setting a required fixed height conflicts as soon as the space between them differs from that height; one of the three must go or become optional. - **Edges instead of the safe area.** A bottom bar pinned to `view.bottomAnchor` slides under the home indicator. - **Frames set alongside constraints.** Once a view is laid out with constraints, the next layout pass overwrites any frame you assign. ## A checklist for a trip card 1. Create the view and set `translatesAutoresizingMaskIntoConstraints = false`. 2. Call `addSubview(_:)` before creating any constraint that relates it to another view. 3. Build constraints from anchors against `view.safeAreaLayoutGuide` (or its margins). 4. Activate them in one `NSLayoutConstraint.activate(_:)` call. 5. Keep references to the constraints you will change and adjust their `constant`.
- Why does activating a constraint between two views sometimes raise an exception?Activation installs the constraint on the closest common ancestor of its two items. If you create and activate it before calling `addSubview(_:)`, the views share no ancestor and UIKit throws. Add every view to the hierarchy first, then activate the batch.
- When the trip card expands, how should its height constraint change?Keep a reference to the constraint and change its `constant`; the header says this performs much better than removing it and adding a new one. To animate, change the constant, then call `layoutIfNeeded()` on the common superview inside a `UIView.animate` block so the new frames are applied as part of the animation.
- Creating an anchor constraint applies it immediately without activation.
- translatesAutoresizingMaskIntoConstraints only matters for views from a storyboard.
- Pinning to the view's top edge keeps content clear of the status bar.
- A custom view should set translatesAutoresizingMaskIntoConstraints to false on itself.
- Constraints can be activated before the two views share a superview.
- Removing and re-adding a constraint is the normal way to change its value.