SwiftUIMidMCQ
What is `GeometryReader` and what are its pitfalls?
Test your knowledge:
Explanation & Code
Answer:
GeometryReader is a container view that exposes the size and coordinate space of its parent, letting you build size-dependent layouts. However it comes with notable downsides.
Code Example:
struct ProportionalView: View {
var body: some View {
GeometryReader { geometry in
Rectangle()
.frame(width: geometry.size.width * 0.5,
height: geometry.size.height * 0.3)
}
}
}
Pitfalls:
- Expands to fill all available space by default — can break layouts
- Triggers layout recalculation which can hurt performance
- Avoid wrapping simple views in it unnecessarily
Better alternatives in many cases:
// Use .containerRelativeFrame for proportional sizing (iOS 17+)
Rectangle()
.containerRelativeFrame(.horizontal) { size, _ in size * 0.5 }
Rate your understanding: