In SwiftUI, what does the alignment parameter of HStack, VStack and ZStack control, and how does a Spacer change a stack's layout?
answer
- main axis versus cross axis
- each stack takes a different alignment type
- children placed, not the stack itself
- Spacer grows along the main axis
basics
~20 sA stack's alignment positions its children on the cross axis: VStack takes a HorizontalAlignment, HStack a VerticalAlignment, ZStack a two-axis Alignment, all defaulting to center. A Spacer expands along the stack's main axis, pushing siblings apart.
solid answer
~40 sA stack's `alignment` places its children along the **cross axis**: `VStack` takes a `HorizontalAlignment` (`.leading`, `.center`, `.trailing`), `HStack` a `VerticalAlignment` (`.top`, `.center`, `.bottom`, `.firstTextBaseline`, `.lastTextBaseline`) and `ZStack` a two-axis `Alignment`; all default to `.center`. Alignment arranges children relative to each other inside the stack, not the stack inside its parent, so a narrow leading-aligned `VStack` still sits centered on screen. `spacing` defaults to `nil`, which uses SwiftUI's default spacing; pass a number to fix the gap. A `Spacer` expands along the main axis, pushing siblings apart and making the stack take the space its parent offers, while a `Divider` only draws a line across the cross axis.
code
swift · 16 linesstruct SettingsRow: View {
let symbol: String
let title: String
let value: String
var body: some View {
HStack(spacing: 12) {
Image(systemName: symbol)
Text(title)
Spacer()
Text(value)
.foregroundStyle(.secondary)
}
.padding(.horizontal)
}
}go deeper
Recall which alignment type each stack takes, that the default is center, and how a Spacer pushes siblings toward the edges.
Explain why alignment arranges children inside the stack rather than placing the stack in its parent, and how a Spacer changes the stack's own size.
Show you can debug a row that refuses to reach an edge by asking who sizes the stack, and keep leading and trailing correct for right-to-left languages.
Argue for adaptive rows built from stacks and spacers over fixed frames, so screens hold up under Dynamic Type, localization and new device sizes.
## The three stacks and their axes SwiftUI ships three basic stacks. Each lays its children out along one **main axis** and uses its `alignment` parameter for the other, the **cross axis**. A `ZStack` is the odd one out: it layers children on top of each other, so it aligns them on both axes at once. | Stack | Children are arranged | `alignment` type | Typical values | |---|---|---|---| | `HStack` | side by side, leading to trailing | `VerticalAlignment` | `.top`, `.center`, `.bottom`, `.firstTextBaseline`, `.lastTextBaseline` | | `VStack` | top to bottom | `HorizontalAlignment` | `.leading`, `.center`, `.trailing` | | `ZStack` | back to front, later children on top | `Alignment` (both axes) | `.topLeading`, `.bottom`, `.center` | The initializers are `HStack(alignment:spacing:content:)`, `VStack(alignment:spacing:content:)` and `ZStack(alignment:content:)`. In the SDK every `alignment` parameter defaults to `.center` and the `spacing` parameters of `HStack` and `VStack` default to `nil`. ## What alignment does, and what it does not do - **It lines children up with each other.** A `VStack(alignment: .leading)` places every child so their leading edges share one vertical line inside the stack. - **It does not move the stack.** Apple's documentation says it plainly: the `alignment` property doesn't position the `VStack` inside its container; it positions the views inside the `VStack`. A `VStack` of two short labels is only about as wide as the wider label, so `.leading` lines them up inside that narrow box and the parent still centers the box on screen. - **Leading is not always left.** In a right-to-left layout direction SwiftUI swaps leading and trailing, which is why stacks speak in leading and trailing rather than left and right. - **It only covers the cross axis.** Position along the main axis comes from the order of the children, the spacing between them and any `Spacer` views. ## Spacing Passing `spacing: nil`, the default, lets SwiftUI insert its default spacing, which Apple's stack article describes as a small amount between each contained view. The `ViewSpacing` documentation adds that a view's spacing preferences can differ by the kind of adjacent view and by platform, so `nil` does not promise one fixed number. Pass a value such as `spacing: 0` or `spacing: 12` when a design needs an exact gap. ## Spacer and Divider on the main axis A `Spacer` is an empty, flexible view. Inside an `HStack` or `VStack` it expands along the main axis as far as the stack allows, pushing its siblings apart; outside any stack it expands on both axes. Where you put it decides the layout: 1. **Before the content**: pushes the content to the trailing (or bottom) end. 2. **Between two views**: sends them to opposite ends of the stack. 3. **On both sides**: keeps the content together in the middle while the stack fills the offered space. A Spacer also changes the stack's own size. The `Spacer` documentation explains that SwiftUI sizes a stack without a spacer up to the combined ideal widths of its children, while a stack that contains a spacer expands to take as much space as its parent allows. A `Divider` is different: it only takes enough room to draw a line across the stack's cross axis and does not expand. How far a spacer may shrink (`minLength`) belongs with SwiftUI's size negotiation rather than with alignment. ## ZStack alignment A `ZStack` has no main axis to space along, so on iOS its initializer, `ZStack(alignment:content:)`, takes only an alignment. That one `Alignment` is shared by every child: - **Order decides depth.** Each successive child is drawn above the one before it, so a backdrop goes first and a label last. - **One anchor for all.** With `.bottomLeading`, every child's bottom-leading corner meets the stack's bottom-leading corner; with the default `.center`, every child is centered on the others. - **Size comes from all children.** The stack must enclose everything it holds, so one large or flexible child makes the whole stack large. When one view should own the size and the rest only decorate it, the `overlay` and `background` modifiers are the better tool. ## A settings row ```swift HStack(spacing: 12) { Image(systemName: "bell.badge") Text("Notifications") Spacer() Text("On") .foregroundStyle(.secondary) } .padding(.horizontal) ``` The `HStack` centers the icon and the texts vertically (its default alignment), keeps 12 points between neighbours and, because of the `Spacer`, stretches across the row so the value lands at the trailing edge. ## Mistakes to avoid - Changing a `VStack`'s alignment to pin it to the screen edge; give the child or the stack flexible width instead. - Expecting an `HStack`'s alignment to choose leading or trailing placement; it only accepts vertical guides. - Reading `spacing: nil` as zero points. - Hard-coding frame widths where a `Spacer` or stack alignment would adapt to Dynamic Type, localization and new screen sizes.
- How would you pin one short Text to the leading edge of the screen when it sits in a VStack?Give that child flexible width, for example `HStack { Text(title); Spacer() }` or `.frame(maxWidth: .infinity, alignment: .leading)`. The child then spans the width the stack is offered, so its content can sit at the leading edge. Changing the `VStack`'s alignment alone does not help, because the stack is only as wide as its widest child.
- How does a ZStack place children of different sizes, and which one is drawn on top?Later children are drawn on top of earlier ones. All children are positioned by one shared `Alignment`: with `.bottomLeading`, for example, every child shares the stack's bottom-leading corner. The `ZStack` itself is sized from all of its children together.
- VStack(alignment: .leading) moves the whole stack to the left edge of the screen.
- An HStack's alignment chooses leading or trailing placement for its children.
- spacing: nil means zero points between a stack's children.
- A Divider expands like a Spacer to fill the stack.
- Leading always means the left side of the screen.