GeometryReader helps your app adjust its layout based on the available space. It makes your app look good on different screen sizes.
GeometryReader for adaptive layouts in iOS Swift
GeometryReader { geometry in
// Use geometry.size.width and geometry.size.height here
// to set sizes or positions
Text("Hello")
.frame(width: geometry.size.width / 2, height: 50)
}The geometry parameter gives you the size and position of the container.
You can use geometry.size.width and geometry.size.height to get the width and height.
GeometryReader { geometry in
Text("Half Width Button")
.frame(width: geometry.size.width / 2, height: 50)
.background(Color.blue)
.foregroundColor(.white)
}GeometryReader { geometry in
VStack {
Text("Width: \(Int(geometry.size.width))")
Text("Height: \(Int(geometry.size.height))")
}
}GeometryReader { geometry in
Circle()
.frame(width: geometry.size.width / 3, height: geometry.size.width / 3)
.position(x: geometry.size.width / 2, y: geometry.size.height / 2)
}This app shows the screen width as text and a green rectangle that fills 80% of the screen width. It adapts automatically to different screen sizes.
import SwiftUI struct ContentView: View { var body: some View { GeometryReader { geometry in VStack { Text("Screen width: \(Int(geometry.size.width))") .font(.headline) .padding() Rectangle() .fill(Color.green) .frame(width: geometry.size.width * 0.8, height: 100) .overlay(Text("80% width rectangle").foregroundColor(.white)) .cornerRadius(10) } .frame(width: geometry.size.width, height: geometry.size.height) } } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
GeometryReader takes all available space by default, so use frames or stacks to control layout.
Use GeometryReader inside flexible containers like VStack or ZStack for best results.
Remember to test on different devices and orientations to see how your layout adapts.
GeometryReader helps you build layouts that adapt to screen size.
You get the container size from geometry.size and use it to set widths, heights, or positions.
This makes your app look good on phones, tablets, and when rotated.