skip to content

In SwiftUI, settings rows in a VStack each show an icon of different width then a label; how do you make every label start at the same x with a custom alignment guide?

level: seniorimportance: should knowfreq 28%

answer

  1. a guide the outer stack honours
  2. one protocol requirement
  3. a static property on HorizontalAlignment
  4. explicit values pass up through rows

basics

~20 s

Define an AlignmentID with defaultValue(in:), expose it as a static HorizontalAlignment, give the outer VStack that alignment, and mark each label with alignmentGuide returning its leading edge. The explicit value passes up through each row's HStack.

solid answer

~40 s

`VStack(alignment: .leading)` aligns the rows themselves, so the labels end up ragged behind icons of different widths; a stack's alignment applies only to its own children. Instead, define a type conforming to `AlignmentID` with `static func defaultValue(in:)`, expose it as `static let labelColumn = HorizontalAlignment(LabelColumn.self)`, and build the outer stack with `VStack(alignment: .labelColumn)`. On each label add `.alignmentGuide(.labelColumn) { d in d[.leading] }`. The explicit value projects up through the row's `HStack`, so the `VStack` shifts each row until the labels' leading edges line up. Views without an explicit value use `defaultValue(in:)`, so pick that default deliberately, and remember the closure only runs when the guide is the container's active alignment.

code

swift · 31 lines
swift
extension HorizontalAlignment {
    private struct LabelColumn: AlignmentID {
        static func defaultValue(in context: ViewDimensions) -> CGFloat {
            context[HorizontalAlignment.leading]
        }
    }

    static let labelColumn = HorizontalAlignment(LabelColumn.self)
}

struct SettingsItem: Identifiable {
    let symbol: String
    let title: String
    var id: String { title }
}

struct SettingsRows: View {
    let items: [SettingsItem]

    var body: some View {
        VStack(alignment: .labelColumn, spacing: 16) {
            ForEach(items) { item in
                HStack {
                    Image(systemName: item.symbol)
                    Text(item.title)
                        .alignmentGuide(.labelColumn) { d in d[.leading] }
                }
            }
        }
    }
}

go deeper

for a junior

Recall that a stack's alignment applies to its own children, so labels inside nested rows need something more than VStack(alignment: .leading).

for a middle

Explain the parts of a custom guide: an AlignmentID with defaultValue(in:), a static HorizontalAlignment, and alignmentGuide on the views to align.

for a senior

Show how explicit values pass up through nested stacks, why the default lands unmarked views on the column, and when a fixed frame or a grid is simpler.

for a principal

Decide whether shared row components should expose a named alignment guide so screens built by different teams line up without per-screen frames.

## Why the built-in alignment is not enough Picture a settings screen: a `VStack` of rows, each row an `HStack` of an SF Symbol and a label. Symbols differ in width, so with `VStack(alignment: .leading)` the rows line up on the icons' leading edges and the labels start at ragged positions. The outer stack cannot see the labels: Apple's documentation notes that by default the alignment you specify for a stack applies only to that stack's own children, which here are whole rows. What you want is a guide that means "the label column", set on the labels deep inside the rows and honoured by the outer `VStack`. That is a **custom alignment guide**. ## Building the guide 1. **Define an identifier.** Create a type that conforms to `AlignmentID` and implements its one requirement, `static func defaultValue(in context: ViewDimensions) -> CGFloat`. The default is used for any view that does not set the guide explicitly. 2. **Expose it.** Add a static property in an extension of `HorizontalAlignment`, built with `HorizontalAlignment(_:)` from your identifier type. A vertical guide works the same way on `VerticalAlignment`. 3. **Assign it to the enclosing stack.** Write `VStack(alignment: .labelColumn)`. The guide only matters where a container aligns by it. 4. **Mark the views to align.** On each label, `alignmentGuide(.labelColumn) { d in d[.leading] }` says "my position on this guide is my leading edge". ## How the value travels The label is not a direct child of the `VStack`; its row's `HStack` is. Apple's article on aligning views across stacks explains that an alignment defined on a stack projects through the enclosed child views: the explicit value set on the label is carried up through its `HStack`, so the row reports its label-column position to the outer stack. The `VStack` then shifts each row until those positions line up, and every label starts at the same x whatever icon precedes it. Some details a senior engineer should know: - **The default is per view.** Any child of the `VStack` without an explicit value, a section title for example, is placed using `defaultValue(in:)`. A default of the view's leading edge drops the title's leading edge onto the label column, indented past the icons. Choose the default on purpose, give such views their own explicit value, or keep them outside the aligned stack. - **`ViewDimensions` has two lookups.** `d[guide]` returns a guide's value, falling back to its default; `d[explicit: guide]` returns an optional that is `nil` when no explicit value has been set. - **The guide must be active.** Apple warns that SwiftUI doesn't invoke an alignment guide closure unless that guide is the container's alignment. - **Right-to-left comes free.** Custom horizontal guides reverse in a right-to-left environment just like the built-in ones; you do not flip the calculation. ## Mistakes that break the column - **Marking the row instead of the label.** `alignmentGuide` on the `HStack` measures the row's own leading edge, which is the icon's, so the column stays ragged. - **Leaving the outer stack on `.leading`.** The labels' explicit values are then never consulted, because no container aligns by the custom guide. - **Stretching every row first.** If each row already fills the offered width with a `Spacer`, shifting rows to line up the labels can make the stack wider than its container, so rows spill past an edge. Apply the guide to rows that hug their content, or give the icon slot a fixed width instead. - **Reusing a built-in guide for a special meaning.** Overriding `.leading` deep inside rows would also change how any other container aligning by `.leading` sees those views; a named custom guide keeps the intent local and readable. ## Alternatives and when they win | Approach | Good when | Cost | |---|---|---| | Custom alignment guide | rows are built from different nested stacks and must share one column | a small amount of setup code; the default needs care | | Fixed icon frame | every row has the same structure and one icon slot | a fixed width that must grow with Dynamic Type | | A grid | the content really is rows and columns | a different container, covered with SwiftUI grids | The custom guide wins when the views that must line up live in separately composed stacks, which is common once rows come from reusable components.

  • How does the custom guide behave in a right-to-left layout?
    It reverses automatically, like the built-in guides. In a right-to-left environment SwiftUI moves each view's origin to its right side and inverts the positive x direction, so `d[.leading]` still names the leading edge and the same code aligns the labels' right-hand starts without any change.
  • A section title in the same VStack sets no explicit value for the guide. Where does it land?
    SwiftUI places it using the guide's `defaultValue(in:)`. With a default of the view's leading edge, the title's leading edge lands on the label column, indented past the icons. Choose the default deliberately, give the title its own explicit value, or keep it outside the aligned `VStack`.

  • VStack(alignment: .leading) lines up the labels because each label is leading in its row.
  • An alignment guide on a view inside a nested HStack cannot affect the outer VStack.
  • alignmentGuide works no matter which alignment the enclosing stack uses.
  • Custom alignment guides must be flipped by hand for right-to-left languages.
  • defaultValue(in:) is used only when no view in the stack sets the guide.