SwiftUI Layout
SwiftUI Layout
Build flexible interfaces with stacks, frames, alignment, and spacing using SwiftUI's layout system.
Stacks and Spacing
Use VStack, HStack, and ZStack to arrange views vertically, horizontally, or in layers.
Spacing and alignment are configurable.
Syntax:
VStack(alignment: .leading, spacing: 8) { ... }HStack { Text("A"); Spacer(); Text("B") }ZStack { Color.blue; Text("Overlay") }
Example
import SwiftUI
struct StacksDemo: View {
var body: some View {
VStack(alignment: .leading, 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 { StacksDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example arranges content using vertical, horizontal, and layered stacks with titles, spacers, and padding.
Frames and Alignment
Adjust size and position with .frame(), .padding(), and .alignmentGuide.
Syntax:
.frame(width: 200, height: 100).frame(maxWidth: .infinity, alignment: .leading).alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
Example
import SwiftUI
struct FrameDemo: View {
var body: some View {
VStack(spacing: 16) {
ZStack(alignment: .topLeading) {
Color.yellow.opacity(0.2)
Text("Top Left").padding(6)
}
.frame(width: 200, height: 100) // fixed size
HStack {
Text("Left")
Spacer()
Text("Right")
}
.frame(maxWidth: .infinity, alignment: .leading) // expand horizontally
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text("Title").font(.title)
Text("Aligned baseline")
.alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
}
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { FrameDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example demonstrates fixed and flexible frames, spacers for distribution, and baseline alignment for text.
Tip: Use Spacer() to push content apart.