How to Set GeometryReader Height According to its Children Height in SwiftUI

Mark van Wijnen
6 min readSep 6, 2023

Intro

If you ever had to deal with dynamic sizes or layouts in SwiftUI 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. 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")
}

--

--

Mark van Wijnen

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs