Skip to content

Container Relative Frames (SwiftUI)

A SwiftUI guide for coding agents. Also covers containerrelativeframe, size relative to parent, carousel item width, geometryreader alternative, count span spacing, paging item sizing.

containerRelativeFrame sizes a view relative to its container without a GeometryReader. Three overloads: fill an axis, divide the container into visible items, or compute the length in a closure.

Fill an axis

Pass the axes to fill and an alignment for the view inside that space.

Text("Hello, World!")
  .containerRelativeFrame([.horizontal], alignment: .leading)
  .background(Color.pink)

Show N items at a time: count and span

The count and span pair is made for carousels in a lazy scroll container. SwiftUI divides the container's length by count, then multiplies by span. With count: 3, span: 1 each item takes one third of the width.

ScrollView(.horizontal) {
  LazyHStack(spacing: 0) {
    ForEach(0..<10) { _ in
      Color.random
        .containerRelativeFrame(.horizontal, count: 3, span: 1, spacing: 0)
    }
  }
}

Keep the spacing parameter in sync with the stack's spacing, since it takes part in the division.

Full control: the closure overload

The closure receives the available length and the axis, and returns the final value. Use it when the fraction differs per axis or needs custom logic.

Color.random
  .containerRelativeFrame([.horizontal], alignment: .center) { length, axis in
    switch axis {
    case .horizontal: return length / 3
    case .vertical: return length / 5
    }
  }

Use this guidance in your coding agent

Install the Better Design MCP once. Your agent then loads this page with one call.

get-swiftui-guide({ topic: "swiftui-container-relative-frames" })
claude mcp add --scope user better-design --transport http https://better-design.com/api/mcp --header "Authorization: Bearer <YOUR_API_KEY>"
Browse related design systems