skip to content

Auto Layout & Constraints

Constraints, anchors, intrinsic content size, and the hugging and compression-resistance priorities that decide which view stretches. The practical test is debugging a conflicting layout from the log.

on this pageshow

explore

questions

6

In UIKit, how do you pin a view to the safe area with layout anchors, and why must translatesAutoresizingMaskIntoConstraints be set to false first?

level: juniorimportance: must knowfreq 80%

answer

  1. typed edges and dimensions
  2. returned constraints start inactive
  3. one call switches on a batch
  4. code-made views default to true
  5. bars, home indicator, extra insets

basics

~20 s

Build 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 s

Every `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 lines
swift
import 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

for a junior

Recall the three steps: turn off translatesAutoresizingMaskIntoConstraints, add the subview, then activate anchor constraints against the safe area guide in one batch.

for a middle

Explain why the flag defaults to true for code-made views and what the generated constraints do, and why activation needs a common ancestor.

for a senior

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.

for a principal

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.
open as a page

In UIKit, a trip card shows a long driver name beside the fare; how do hugging and compression resistance decide which label truncates or stretches?

level: middleimportance: must knowfreq 78%

basics

~20 s

Each label's intrinsic size yields two optional constraints per axis: compression resistance against shrinking and hugging against growing. With too little room the lower compression resistance truncates; with spare room the lower hugging stretches. Equal priorities leave UIKit to choose.

open as a page

In UIKit, a trip card prints 'Unable to simultaneously satisfy constraints' to the console; how do you read that log and decide which constraint to make optional?

level: seniorimportance: must knowfreq 66%

basics

~20 s

The log lists required constraints that cannot all hold and names the one UIKit breaks to recover. Add up one axis, find the constraint that is really a preference, and give it an optional priority before activating it.

open as a page

In UIKit, how does UIKeyboardLayoutGuide keep a promo-code text field above the keyboard, and what keyboard-notification code does it replace?

level: middleimportance: should knowfreq 55%

basics

~20 s

Since iOS 15 every view has a keyboardLayoutGuide that tracks the docked keyboard; pinning the field's bottom to its topAnchor keeps it above the keyboard. It replaces observing keyboard frame notifications and adjusting a bottom constraint's constant by hand.

open as a page

In UIKit, how do a UIStackView's axis, distribution, alignment and spacing place a trip card's two side-by-side buttons, and when is fillEqually better than fill?

level: middleimportance: should knowfreq 62%

basics

~20 s

Axis picks a row or a column, distribution sizes views along it, alignment places them across it, and spacing sets the gaps. fill sizes buttons from their intrinsic widths and priorities; fillEqually gives both the same width whatever their titles.

open as a page

In UIKit, a custom fare badge view overrides intrinsicContentSize, yet keeps its old width after the fare text changes; why, and what is the fix?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Auto Layout uses the intrinsicContentSize it last read until the view says it changed, and the badge never said so. Call invalidateIntrinsicContentSize() whenever the text changes; setNeedsLayout() or setNeedsDisplay() alone rerun layout or drawing with the old size.

open as a page