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
Demo.swift
ContentView.swift
App.swift
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()
}
}
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
Demo.swift
ContentView.swift
App.swift
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()
}
}
Leave a Reply