Snippets
SwiftUI PreferenceKey for Layout Measurement
Pass child measurements up the view tree with PreferenceKey when a parent needs information children know first.
6 min readUpdated 2026-06
import SwiftUI
private struct WidthKey: PreferenceKey {
static var defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
struct MeasuredTitle: View {
@State private var width: CGFloat = 0
var body: some View {
Text("Overview")
.background {
GeometryReader { proxy in
Color.clear.preference(key: WidthKey.self, value: proxy.size.width)
}
}
.onPreferenceChange(WidthKey.self) { width = $0 }
}
}Implementation notes
Preferences flow upward, which makes them a good fit for child-to-parent layout information.
The reduce function defines how multiple children combine their values.
Color.clear with GeometryReader is a common measuring pattern, but keep it contained.
Checklist
Avoid updating state in a way that causes endless layout changes.
Choose reduce behavior deliberately: max, sum, append, or last value.
Name keys for the information they publish.
Related reference
SwiftUI Alignment Guides and Coordinate Space
Reach for alignment guides and coordinate spaces when default stack alignment is not expressive enough.
SwiftUI Frame, Padding, and Layout Priority
Control layout by combining flexible frames, padding, fixedSize, and layoutPriority rather than guessing with offsets.
SwiftUI Overlay, Background, and zIndex
Layer views deliberately with background, overlay, and zIndex while keeping the base layout stable.