Alignment
SwiftUI ⟩ View ⟩ Layout ⟩
Aligning Views Across Stacks - align views across multiple stacks
SwiftUI Lab ⟩ Alignment Guides in SwiftUI
Swift with Majid ⟩ Alignment guides in SwiftUI
Align Within a Stack
default alignment
built-in alignments
adjust alignment guide of indivisual views

ZStack {
/// ⭐️ 1. default alignment: `.center`
HStack {
Image(systemName: "mic")
Text("Connecting").font(.caption)
Text("Bryan").font(.title)
}
.padding()
.border(Color.blue, width: 1)
.overlay(HLine(color: .orange))
}
注意:一般的 Image 不支援 .firstTextBaseline,但 SF Symbols 支援。
Align Across Stacks
use custom alignment
use built-in alignment

/// ⭐️ 1. Define a Custom Alignment
extension VerticalAlignment {
/// ⭐️ 1.1 define custom alignment for image titles.
private struct ImageTitleAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
// default to bottom alignment if no guides are set.
context[VerticalAlignment.bottom]
}
}
/// ⭐️ 1.2 define a convenience alignment guide name
static let imageTitle = VerticalAlignment(
ImageTitleAlignment.self
)
}
struct AcrossStacks: View {
var body: some View {
/// ⭐️ 2. Assign custom alignment to parent view
/// When you assign an alignment on a stack,
/// it projects through enclosed child views.
HStack(alignment: .imageTitle, spacing: 32) {
VStack {
Image(systemName: "bell")
.resizable().scaledToFit().padding().foregroundColor(.red)
Text("Bell Peppers").font(.title)
/// ⭐️ 3. Within each nested stack, apply `.alignmentGuide()`
/// to the view you want to align with.
.alignmentGuide(.imageTitle) { dim in
dim[.firstTextBaseline]
}
}
VStack {
Image(systemName: "memorychip")
.resizable().scaledToFit().padding().foregroundColor(.green)
Text("Chili Peppers").font(.title)
/// ⭐️ 3.
.alignmentGuide(.imageTitle) { dim in
dim[.firstTextBaseline]
}
Text("Higher levels of capsicum").font(.caption)
}
}.overlay(HLine(), alignment: Alignment(horizontal: .center, vertical: .imageTitle))
}
}
Last updated
Was this helpful?