skip to content

How does SwiftUI's ViewThatFits choose which child to display, and how do you order its children for a card that must adapt?

level: middleimportance: should knowfreq 38%

answer

  1. order of preference
  2. ideal size, not squeezed size
  3. which axes are constrained
  4. first that fits, not biggest

basics

~20 s

ViewThatFits tries its children in the order written and shows the first whose ideal size fits the proposed size on the constrained axes, both by default; list the preferred, roomiest arrangement first and a compact fallback last.

solid answer

~40 s

`ViewThatFits` (iOS 16) holds alternative arrangements and evaluates them in order, displaying the first child whose ideal size fits the size its parent proposed. By default it checks both axes; `ViewThatFits(in: .horizontal)` checks only width, which is what I want for a row. Because it compares ideal sizes, a `Text` counts at its full unwrapped width, so an `HStack` of cooking time and servings is rejected before it would truncate, and a stacked `VStack` takes over. That also makes it react to larger Dynamic Type sizes without extra code. I order candidates from most preferred to the smallest fallback, keep them light, and keep any state above the container, since each candidate is a separate view.

code

swift · 20 lines
swift
import SwiftUI

struct RecipeMetaRow: View {
    let minutes: Int
    let servings: Int

    var body: some View {
        ViewThatFits(in: .horizontal) {
            HStack(spacing: 12) {
                Label("\(minutes) min", systemImage: "clock")
                Label("Serves \(servings)", systemImage: "person.2")
            }
            VStack(alignment: .leading, spacing: 4) {
                Label("\(minutes) min", systemImage: "clock")
                Label("Serves \(servings)", systemImage: "person.2")
            }
            Label("\(minutes) min", systemImage: "clock")
        }
    }
}

go deeper

for a junior

Recall that ViewThatFits shows one of several alternatives, chosen in the order you list them, and that it needs iOS 16 or later.

for a middle

Explain the ideal-size test, what the in: axes parameter changes, and why the order of candidates matters more than their sizes.

for a senior

Show when you would use it instead of size classes or measured geometry, and how you keep state and expensive work out of the candidates.

for a principal

Discuss how a component library can make its controls fit by construction with ViewThatFits, so screens do not each reimplement adaptation rules.

## What ViewThatFits is `ViewThatFits`, available since iOS 16, is a container that holds several alternative arrangements of the same content and displays exactly one of them. Apple's documentation calls it "a view that adapts to the available space by providing the first child view that fits." You list the candidates in order of preference, and SwiftUI picks one during layout. ## How it chooses The rule in Apple's documentation has three parts: 1. **Order**: it evaluates its children in the order you wrote them. 2. **Ideal size**: for each child it considers the child's **ideal size**, the size the view would take if its parent imposed no limit. 3. **Constrained axes**: it compares that ideal size with the size its own parent proposed, on the axes it is told to constrain, and selects the first child that fits. The initializer is `init(in axes: Axis.Set = [.horizontal, .vertical], content:)`. By default both axes count; `ViewThatFits(in: .horizontal)` checks only the width. The `in:` label names the axes to **measure**; it does not lay the children out side by side. ## Ideal size is the key idea Because the fit test uses ideal sizes, a `Text` competes with its whole string laid out without wrapping, the size `fixedSize()` would give it, not with a wrapped or truncated version its parent could squeeze it into. That is what makes `ViewThatFits` useful: the roomy arrangement is rejected **before** it would wrap or truncate, and the next candidate is used instead. It also makes `ViewThatFits` respond to Dynamic Type without extra code. When someone chooses a larger text size, every label's ideal size grows, the wide arrangement stops fitting, and a narrower one takes over. ## Ordering the children Apple notes that the order is usually largest to smallest, but not always, because a candidate can fit on one constrained axis and not on the other. For the metadata row on a recipe card: - First, an `HStack` with the cooking time and the servings side by side. - Then a `VStack` with the same two labels stacked. - Last, the cooking time alone, the smallest fallback. Put the arrangement you prefer first and one that fits the smallest space you support last. ## ViewThatFits, size classes and text size | Signal | What it reflects | Good for | |---|---|---| | `ViewThatFits` | the space proposed to this view | a component that must fit wherever it is placed | | `horizontalSizeClass` | a two-value bucket for the window's width | screen-level structure | | `dynamicTypeSize` | the text size the person chose | an explicit rule, such as one column at accessibility sizes | `ViewThatFits` is the local tool. It behaves the same in a grid cell, a sidebar column or a narrow Split View window, because it reacts to the space it is actually given rather than to the device or the window as a whole. ## Pitfalls - **Expecting it to squeeze a child.** It picks a candidate; it does not shrink, scale or truncate one into place. - **Measuring the wrong axes.** With the default of both axes, a candidate can be rejected for being too tall when only width mattered; pass `in: .horizontal` for a row that should adapt to width alone. - **Expecting the biggest candidate that fits.** It takes the first one that fits in your order, so a small candidate listed early wins over a larger one listed later. - **Keeping state inside a candidate.** Each child is a separate view, so state held inside one arrangement does not carry over when the choice flips; keep it in the view that owns the `ViewThatFits`. - **Heavy alternatives.** Because candidates are evaluated in turn, keep them small and similar rather than listing whole screens. ## Where it sits among the layout tools `ViewThatFits` decides **which** arrangement to show. It is not the tool for computing a column count (adaptive `GridItem` columns do that), for reading a measured size (covered with geometry), or for animating between two layouts (covered with custom layout containers). A useful way to review a pull request that adds one: cover the code and ask what the component should look like in the narrowest space it can be placed in, at the largest text size. That answer should be the last candidate. Then ask what it should look like with room to spare; that is the first. Everything in between is optional, and two or three candidates are usually enough.

  • When would you choose ViewThatFits over reading horizontalSizeClass?
    When the decision depends on the space this particular component gets rather than on the window. A metadata row inside a grid cell, a sidebar or a narrow Split View pane can be cramped even when the window is regular width. `ViewThatFits` reacts to the proposed size wherever the view is placed, while the size class is one bucket for the whole window and suits screen-level structure.
  • Why does a ViewThatFits row often switch arrangement at large accessibility text sizes without any code reading dynamicTypeSize?
    Larger text makes every label's ideal size larger. `ViewThatFits` compares ideal sizes with the proposed size, so the side-by-side candidate stops fitting at some text size and the next candidate is chosen. Reading `dynamicTypeSize` is still useful when you want an explicit rule, such as a single grid column at accessibility sizes.

  • ViewThatFits shrinks or truncates a child until it fits.
  • ViewThatFits picks the largest child that fits, whatever the order.
  • ViewThatFits(in: .horizontal) lays its children out side by side.
  • A Text that would wrap onto two lines still counts as fitting.
  • ViewThatFits decides by reading the device's size class.