Using GeometryReader in SwiftUI to Build Relative Layouts
Understand how GeometryReader can be used to create relative layouts.
While much of the time developers can utilize stacks and allow SwiftUI to adjust its own layout, there are times when we want to have more control over how views will be displayed on the screen. We can achieve this goal by using GeometryReader.
Let’s say, for example, that we have a Text view and give it a yellow background so that we can see the frame of our view. By default, SwiftUI will place the Text in the center and only take up the space required for the view.
What if we want the view to take up the full width regardless of how much text it contains? This is where GeometryReader comes into play. According to Apple, GeometryReader is "a container view that defines its content as a function of its own size and coordinate space."
Like most everything in SwiftUI, GeometryReader is a view but with the added benefit of exposing additional information to its child views. So if we want our child view to cover half the width of the screen, we can put the view inside a GeometryReader and set its width to half the width of the geometry.
You’ll notice that the child view is now half the width of the screen, but it also moved to the top leading edge instead of being centered. GeometryReader adjusts itself to take up as much available space as it can.
We can see this more clearly by setting the GeometryReader background color to blue. The blue background of the GeometryReader covers everything within the safe area insets, but the Text itself is a smaller view within GeometryReader's area.
This may be the desired result, but for example purposes we want to keep the Text centered. We have a few options to achieve this, one being to wrap Text in a combination of stacks and spacers or adjusting a stack's frame to fill the full space taken by GeometryReader. But since we are already using GeometryReader, we have access to information about our child view's parent.
Within GeometryReader we can simply add a position using the geometry.frame(in: .local) to (midX, midY). Position will put the center of the view at the stated coordinates within its parent.
A benefit of GeometryReader is that because it adjusts to fill all available space, its child views will make adjustments based on how much screen space GeometryReader itself has. If we add an HStack outside of the GeometryReader and add a preceding Image view, our Text will decrease its width to remain at half the width of its superview, the GeometryReader.
Because GeometryReader is a SwiftUI view that passes information about its coordinate space to its child views, it gives us more control when laying out our views using relative positioning and sizes.
Questions or comments? Feel free to contact us directly and follow our Application Development topic area to get alerts on the latest in the software space.