How SwiftUI sizes and places views
Layout in SwiftUI is a short conversation, repeated down the tree:
- The parent offers a size: “You can have up to 390 by 200 points.”
- The child decides its own size: a
Texttakes just enough for its words; aColortakes everything offered; anImagetakes its own size unless it’s resizable. - The parent places the child inside its own area, centered by default.
The child always has the last word on its size. That explains most surprises:
.frame(width: 100)doesn’t resize the text: it’s a new view, 100 points wide, that offers 100 points to the text and centers it.- Modifier order matters.
.padding().background(.yellow)colors the padding too;.background(.yellow).padding()colors only behind the text, then adds empty space around it. - Stacks give space first to children that can’t grow much, and share the rest.
.layoutPriority(1)makes a child go first.
The layout protocol is propose, choose, place: a parent proposes a ProposedViewSize (each dimension can be a value, nil for “your ideal size”, 0 or infinity), the child returns its size, and the parent positions it. Modifiers are views, so .frame, .padding and .fixedSize() are layout participants that change proposals; fixedSize() proposes nil (ideal size) in one or both axes. HStack divides space by sorting children by flexibility (the range between their minimum and maximum size for the proposal) and by layoutPriority, offering the least flexible first. GeometryReader is greedy (it accepts the whole proposal) and places its content at the top-leading corner, which is why it breaks layouts when used for measuring; measure with onGeometryChange(for:of:action:) or a background GeometryReader instead. ViewThatFits picks the first child whose ideal size fits. The Layout protocol (iOS 16) gives you the same primitives: sizeThatFits and placeSubviews, with optional caching.
struct FlowLayout: Layout {
var spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let rows = arrange(maxWidth: proposal.width ?? .infinity, subviews: subviews)
let width = rows.map(\.width).max() ?? 0
let height = rows.last.map { $0.y + $0.height } ?? 0
return CGSize(width: proposal.width ?? width, height: height)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
for row in arrange(maxWidth: bounds.width, subviews: subviews) {
for item in row.items {
subviews[item.index].place(at: CGPoint(x: bounds.minX + item.x, y: bounds.minY + row.y),
proposal: .unspecified)
}
}
}
private struct Row {
var items: [(index: Int, x: CGFloat)] = []
var y: CGFloat = 0
var width: CGFloat = 0
var height: CGFloat = 0
}
private func arrange(maxWidth: CGFloat, subviews: Subviews) -> [Row] {
var rows = [Row()]
var x: CGFloat = 0
for (index, subview) in subviews.enumerated() {
let size = subview.sizeThatFits(.unspecified) // each tag's ideal size
if x > 0, x + size.width > maxWidth { // doesn't fit: start a new row
let y = rows[rows.count - 1].y + rows[rows.count - 1].height + spacing
rows.append(Row(y: y))
x = 0
}
rows[rows.count - 1].items.append((index, x))
rows[rows.count - 1].height = max(rows[rows.count - 1].height, size.height)
rows[rows.count - 1].width = x + size.width
x += size.width + spacing
}
return rows
}
}
// Use it like a stack
FlowLayout {
ForEach(recipe.tags, id: \.self) { tag in
Text(tag).padding(.horizontal, 10).padding(.vertical, 4)
.background(.thinMaterial, in: Capsule())
}
}
// Two layouts, SwiftUI picks the first one that fits
ViewThatFits(in: .horizontal) {
HStack { price; addToCartButton }
VStack(alignment: .leading) { price; addToCartButton }
}sizeThatFitsanswers “how big are you, if offered this much?”. The layout lays out the tags in rows and reports the total height.placeSubviewsputs each tag at its position, row by row.subview.sizeThatFits(.unspecified)asks each tag for its natural size, the same question a stack asks.ViewThatFitstries theHStackfirst and falls back to theVStackon narrow screens or with large text sizes.
Predict the output
Text("Sale").background(.yellow).padding(20) and Text("Sale").padding(20).background(.yellow). How do they look different?
Each modifier wraps everything before it. In the first, the background is applied to the text alone, then padding adds empty space around the yellow. In the second, padding first makes a bigger view, and the background fills all of it. When a background, border or tap area looks the wrong size, check the modifier order.
Practice: a row that doesn’t squeeze the price
Tap the line with the bug.
HStack {
Text(product.name)
.font(.headline)
Spacer()
Text(product.price, format: .currency(code: "EUR"))
.font(.headline)
}Hint: With a very long product name, which Text gets truncated? Which one should keep its full width?
With a long name, the HStack shares the width between both texts, and the price can end up truncated as “€1,2…”. Nothing tells the stack the price is more important. Give it priority, or make it refuse to shrink:
HStack {
Text(product.name).font(.headline).lineLimit(2)
Spacer()
Text(product.price, format: .currency(code: "EUR"))
.font(.headline)
.fixedSize() // always its full ideal width
}Now the name wraps onto a second line, and the price always shows in full.
Measure without breaking the layout
A collapsible text shows “Read more” only when the full text is taller than three lines. You need the full text’s height. A teammate wrapped the text in a GeometryReader, and now it fills the whole screen. What would you do instead?
›
There’s a modifier that reports a size to you without taking part in the layout.
SolutionTry it yourself first
Keep the text’s normal layout and read its size with onGeometryChange:
@State private var fullHeight: CGFloat = 0
Text(article.body)
.fixedSize(horizontal: false, vertical: true) // full height, not truncated
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.size.height
} action: { height in
fullHeight = height
}GeometryReader takes all the space offered and puts its content in the top-left corner, so it changes the layout it’s trying to measure. onGeometryChange only reports.
Layout details worth knowing
- Alignment guides:
.alignmentGuide(.firstTextBaseline) { … }and customAlignmentIDs align views across different stacks (a label column, icons on baselines). - Layout caching:
Layoutcan declare aCachetype and compute measurements once inmakeCache;updateCacheruns when subviews change. Worth it for large flows. AnyLayoutswitches betweenHStackLayoutandVStackLayout(for example ondynamicTypeSize) while keeping subview identity, so the switch can animate.- Safe areas and
containerRelativeFrame(iOS 17) size views relative to the nearest container, such as paging cards at 80% of the scroll view’s width, without aGeometryReader.
- Propose → choose → place; the child decides its size. Proposals can be
nil(ideal), 0 or infinity. - Modifiers are views: order changes layout.
.frameproposes and aligns;fixedSize()proposesnil. - Stacks offer space least-flexible first, adjusted by
layoutPriority. GeometryReaderis greedy and top-leading: measure withonGeometryChangeinstead.ViewThatFitsfor fallbacks,AnyLayoutto switch stacks with identity preserved,containerRelativeFramefor container-relative sizes.- Custom
Layout:sizeThatFits+placeSubviews, optional cache.
Check this part
Who decides a Text’s final size in SwiftUI?
Why does wrapping a row in GeometryReader often make it fill the screen?
What does fixedSize() change?
Which tool switches between an HStack and a VStack while keeping subview identity?