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
}
}