Using ViewThatFits to replace GeometryReader in SwiftUI
This article shows how to use the new ViewThatFits released at WWDC 2022 to replace GeometryReader when building views in SwiftUI.

In this article, I will describe how I used the brand new ViewThatFits
in my Basketball Coach app.
Before ViewThatFits
Until iOS 15 it was not easy to write a view that adapts its content based on the available space. Let's take a look at PlayerRow
, a view that displays a player's information, such as the number and full name.

This row is used in different contexts and, of course, on different devices and orientations. In order to adapt its content my approach was the following:
1. I wrapped the view in a GeometryReader
2. I used its GeometryProxy
's size to get the available width
3. I applied a little bit of math
var body: some View {
GeometryReader { proxy in
if proxy.size.width > 180 {
// display full row
} else if proxy.size.width > 100 {
// display row with short name
} else {
// display only the left component
}
}
}
This works. It is not the most declarative solution though. So let's have a look at how this works with a ViewThatFits.
Become a free member or log in to proceed.