SwiftUI Layout GeometryReader
SwiftUI Layout: GeometryReader
Read parent size and position to build responsive layouts with GeometryReader.
GeometryReader
Use GeometryReader to read parent size and position to build responsive layouts.
Example
import SwiftUI
struct GeometryDemo: View {
var body: some View {
GeometryReader { geo in
VStack(spacing: 12) {
Text("Width: \(Int(geo.size.width))")
Text("Height: \(Int(geo.size.height))")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(.orange.opacity(0.1))
}
}
import SwiftUI
struct ContentView: View {
var body: some View { GeometryDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
Responsive Positioning
Position elements based on container size using GeometryReader, alignment, and offset.
Syntax:
GeometryReader { geo in ... }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing).offset(x: 0, y: -12)
Example
import SwiftUI
struct GeometryPositionDemo: View {
var body: some View {
GeometryReader { geo in
ZStack {
Color.orange.opacity(0.1)
Text("Bottom Right")
.padding(8)
.background(.thinMaterial, in: Capsule())
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
.offset(x: 0, y: -12)
}
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { GeometryPositionDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}