How to Set GeometryReader Height According to its Children Height in SwiftUI
--
Intro
If you ever had to deal with dynamic sizes or layouts in SwiftUI, for example, to build a responsive layout that adapts to different devices and orientations, you will most certainly came across GeometryReader
. If you did you may also be frustrated to find out that GeometryReader
itself is a container view that just returns a flexible preferred size to its parent layout. To put in simpler words, it just takes as much space as it can. Which at first is nice, because it tells us the size that we can work with. The frustrating part is that it will not automatically size back to fit its children. Meaning you are stuck with a view that takes up all the space, which may not be desired.
This story is not about what GeometryReader
is or how to use GeometryReader
I may save that for another story. It is focused mainly on answering the question how can we set the height of the GeometryReader
view to fit its children.
Problem
Let’s start with a simple layout.
VStack {
Text("Header")
VStack {
Text("Line 1")
Text("Line 2")
Text("Line 3")
}
.padding()
.background(.red)
Text("Footer")
}
VStack
does the layout work for us. It will vertically place the children and it will end up with a frame that is the size of its children. Meaning it will take no more space then that. We could build something similar to VStack
but to keep this story simple and easy to follow we stick to it.
Now as soon as we throw GeometryReader
in the mix our layout changes.
VStack {
Text("Header")
GeometryReader { proxy in
VStack {
Text("Line 1")
Text("Line 2")
Text("Line 3")
}
}
.padding()
.background(.red)
Text("Footer")
}