How would you build a wrapping row of filter chips with SwiftUI's Layout protocol, and how should sizeThatFits treat the proposed width?
answer
- measure first, then break rows
- ideal size from .unspecified
- proposed width is the wrap limit
- nil width means one row
- one helper for both methods
basics
~20 sMeasure each chip's ideal size, start a new row whenever the next chip would pass the proposed width, and return the widest row and total height; placeSubviews repeats that row-breaking against bounds.width so placement matches the reported size.
solid answer
~40 sI'd write a `FlowLayout` that conforms to `Layout`. In `sizeThatFits(proposal:subviews:cache:)` I measure every chip with `subview.sizeThatFits(.unspecified)`, then walk them left to right, starting a new row when the next chip plus spacing would exceed `proposal.width`; I return the widest row and the summed row heights plus line spacing. If `proposal.width` is `nil` the parent wants my ideal size, so I treat the limit as unlimited and report one row. In `placeSubviews(in:proposal:subviews:cache:)` I run the same row-breaking against `bounds.width`, offset from `bounds.minX` and `bounds.minY`, and call `place(at:anchor:proposal:)` with each chip's measured size. One helper used by both methods keeps them from disagreeing, and a chip wider than the row gets its own row, or a capped proposal so its text truncates.
code
swift · 36 linesimport SwiftUI
struct FlowLayout: Layout {
var spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let frames = rowFrames(for: subviews, maxWidth: proposal.width ?? .infinity)
return CGSize(width: frames.map(\.maxX).max() ?? 0,
height: frames.map(\.maxY).max() ?? 0)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
for (index, frame) in rowFrames(for: subviews, maxWidth: bounds.width).enumerated() {
subviews[index].place(
at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY),
proposal: ProposedViewSize(frame.size))
}
}
private func rowFrames(for subviews: Subviews, maxWidth: CGFloat) -> [CGRect] {
var frames: [CGRect] = []
var origin = CGPoint.zero
var rowHeight: CGFloat = 0
for subview in subviews {
let size = subview.sizeThatFits(.unspecified)
if origin.x > 0, origin.x + size.width > maxWidth {
origin = CGPoint(x: 0, y: origin.y + rowHeight + spacing)
rowHeight = 0
}
frames.append(CGRect(origin: origin, size: size))
origin.x += size.width + spacing
rowHeight = max(rowHeight, size.height)
}
return frames
}
}go deeper
Recall that wrapping chips need a custom Layout, because stacks never move a child onto a new line.
Walk through measuring ideal sizes, breaking rows at the proposed width, and returning the widest row with the total height.
Show the shared row-breaking helper, nil-width handling, bounds origin offsets, capped proposals for oversized chips, and when a cache is worth adding.
Weigh one vetted flow layout in the shared library against ad-hoc copies, and define its spacing, alignment and truncation contract.
## Why stacks cannot do this A cloud of filter chips ("Open now", "Under $20", "4 stars and up") should fill a row and wrap onto the next when it runs out of width. Nested stacks cannot express that, because an `HStack` never moves a child onto a new line. Deciding where a row ends requires **measuring the chips before placing them**, against the width the parent offers, and that is exactly what the **`Layout` protocol** (iOS 16) gives a custom container. ## The algorithm A flow layout is a greedy line-breaker: 1. **Measure.** Ask each proxy for its ideal size with `subview.sizeThatFits(.unspecified)`. An unspecified proposal means "how big do you want to be?", which for a chip is its label plus padding. 2. **Break rows.** Walk the sizes in order with a running x position. If the current row already holds a chip and the next one plus spacing would pass the limit, start a new row at x = 0, moving down by the tallest chip of the finished row plus the line spacing. 3. **Report.** `sizeThatFits(proposal:subviews:cache:)` returns the widest row as the width and the bottom of the last row as the height. 4. **Place.** `placeSubviews(in:proposal:subviews:cache:)` runs the same breaking against `bounds.width` and calls `place(at:anchor:proposal:)` on each chip, offset by `bounds.minX` and `bounds.minY`. Putting steps 1 and 2 in one private helper that both methods call is the simplest way to guarantee that the size you report and the positions you commit agree. ## What the proposed width means The proposal is the heart of the question: - **A concrete width**, say 343 points for a padded screen on an iPhone, is the wrap limit. - **A `nil` width** means the parent is asking for the ideal size, for example when it probes before deciding. The honest ideal for a flow is one long row, so treat `nil` as unlimited rather than as zero; treating it as zero puts one chip on every row. - **The height is usually ignored**: a flow grows downward and reports the height its rows need. Because a parent can ask for a size more than once, `sizeThatFits` must be a pure function of its inputs. Do not save "the last width" from one call and reuse it in `placeSubviews`; read `bounds` there. ## Details that separate a working answer from a good one - **Spacing.** A fixed `spacing` parameter is simplest. To follow platform spacing instead, read each neighbour pair's preference with `subviews[i].spacing.distance(to: subviews[i + 1].spacing, along: .horizontal)`, built on each chip's `ViewSpacing`. - **Oversized chips.** A chip wider than the row lands alone on its row and overflows. To make it truncate, place it with a proposal capped at the row width, `ProposedViewSize(width: min(size.width, bounds.width), height: nil)`. - **Row alignment.** Chips of different heights look better centred in their row: place each at the row's vertical middle with `anchor: .leading`. - **Centred or trailing rows.** Keep each row's total width and add `(bounds.width - rowWidth) / 2` to centre it. - **Per-chip data.** If one chip must always start a new row, a custom `LayoutValueKey` lets the layout read that flag from the chip's proxy. - **Repeated measuring.** Without a cache both methods measure every chip; that is fine for a dozen chips, and a cache from `makeCache(subviews:)` is the tool if profiling shows otherwise. ## Why not GeometryReader or ViewThatFits | Approach | What goes wrong | |---|---| | `GeometryReader` around the chips | it returns a flexible size to its parent, so the container stops fitting its content and you still compute rows by hand | | `ViewThatFits` | it picks the first of several fixed alternatives that fits; it cannot invent a wrap point | | Nested `HStack`s from a pre-split array | the split is guessed in advance and breaks at other widths and text sizes | | A custom `Layout` | it measures the real chips against the real proposal and reports a true size | A flow layout is a clear case of what Apple's documentation means by "behavior that you can't achieve with the built-in layout tools".
- Why pass the measured size as the proposal in place(at:anchor:proposal:)?The proposal given to `place` is the offer the chip lays itself out against. Passing the size you measured keeps placement identical to measurement, and it is where you cap an oversized chip, for example `ProposedViewSize(width: min(size.width, bounds.width), height: nil)`, so its label truncates instead of overflowing the row.
- How would you centre each row of chips?Break rows first and keep each row's total width, then in `placeSubviews` add `(bounds.width - rowWidth) / 2` to every x in that row, or `bounds.width - rowWidth` to align it to the trailing edge. The reported size does not change, only where each row starts, so `sizeThatFits` stays as it is.
- A flow layout can be built from nested HStacks if you split the array first.
- When proposal.width is nil, a flow layout should report a width of zero.
- placeSubviews can reuse the width saved from the last sizeThatFits call.
- Each chip should be measured with .infinity to get its natural width.
- GeometryReader is the standard way to wrap chips onto new lines.