Snippets
SwiftUI Alignment Guides and Coordinate Space
Reach for alignment guides and coordinate spaces when default stack alignment is not expressive enough.
5 min readUpdated 2026-06
import SwiftUI
private extension HorizontalAlignment {
enum FormLabel: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[.leading]
}
}
static let formLabel = HorizontalAlignment(FormLabel.self)
}
struct AlignedFormRow: View {
var body: some View {
VStack(alignment: .formLabel) {
Label("Email", systemImage: "envelope")
.alignmentGuide(.formLabel) { $0[.leading] }
TextField("name@example.com", text: .constant(""))
}
}
}Implementation notes
alignmentGuide changes how a view reports its alignment, which is different from visually moving it with offset.
Named coordinate spaces make geometry reads more robust than relying only on global positions.
When many screens need similar measurement behavior, consider a custom Layout or reusable helper.
Checklist
Name custom alignments after the layout meaning, not a pixel position.
Avoid geometry reads inside every row of a large list unless needed.
Test when text wraps to multiple lines.
Related reference
SwiftUI PreferenceKey for Layout Measurement
Pass child measurements up the view tree with PreferenceKey when a parent needs information children know first.
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.