ViewThatFits (iOS 16) measures the available space and renders the first of its children that fits. It replaces most GeometryReader measure-and-branch code, which is easy to get wrong and easy to break layout with.
Order From Biggest to Smallest
Give it up to 10 views in the ViewBuilder closure. It walks them in order and places the first that fits, so list the preferred, larger layout first and the compact fallback last.
ViewThatFits {
HugeView()
MediumView()
SmallView()
}
If nothing fits, the last view is placed anyway. Make the last child the one that degrades gracefully.
Constrain the Measured Axis
By default both axes count. Pass an axis to measure only one, for example a row that should fall back to a column when the width runs out, whatever the height.
ViewThatFits(in: .horizontal) {
HStack {
Image(systemName: "star")
Text("Long text here")
}
VStack {
Image(systemName: "star")
Text("Long text here")
}
}
The Selection Algorithm
- Measure the available space on the chosen axis, or both.
- Measure the first child; place it if it fits.
- Otherwise measure the next child, and so on.
- Place the last child when none fit.