SwiftUI Layout Stacks
SwiftUI Layout: Stacks
Arrange views vertically, horizontally, or in layers using VStack, HStack, and ZStack.
Examples
Example
import SwiftUI
struct StackDemo: View {
var body: some View {
VStack(spacing: 12) {
Text("Title").font(.title)
HStack {
Text("Left")
Spacer()
Text("Right")
}
ZStack {
Color.blue.opacity(0.1)
Text("Overlay")
}
}.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { StackDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
Overlays and Alignment
Layer content with ZStack and control placement using alignment and alignmentGuide.
Syntax:
ZStack(alignment: .topLeading) { ... }.alignmentGuide(.top) { d in d[.bottom] }
Example
import SwiftUI
struct OverlayDemo: View {
var body: some View {
ZStack(alignment: .topLeading) {
Image(systemName: "rectangle.fill").resizable().foregroundStyle(.blue.opacity(0.15))
Text("Badge")
.padding(6)
.background(.ultraThinMaterial, in: Capsule())
.alignmentGuide(.top) { d in d[.bottom] } // custom guide
}
.frame(width: 220, height: 120)
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { OverlayDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}