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
clike
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))
}
}
clike
import SwiftUI
struct ContentView: View {
var body: some View { GeometryDemo() }
}
clike
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
clike
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)
}
}
}
}
clike
import SwiftUI
struct ContentView: View {
var body: some View { GeometryPositionDemo() }
}
clike
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}