Pick the layout that fits the space
Trying to work out which layout fits best? Don't bother—offer SwiftUI a few versions of a view, from widest to narrowest, and it shows the first one that fits. No size classes or geometry readers.
iOS 16+macOS 13+ Swift 5.9
A row of buttons that fits on an iPad overflows on a small iPhone, and a label that fits in English is cut off in German or at large text sizes. ViewThatFits takes a list of alternatives and picks the first that fits without truncating.
import SwiftUI
struct ActionsView: View {
var body: some View {
VStack(spacing: 24) {
// Side by side when there is room, stacked when there is not.
ViewThatFits(in: .horizontal) {
HStack { buttons }
VStack { buttons }
}
// The longest label that fits.
ViewThatFits(in: .horizontal) {
Label("Add to favourites", systemImage: "star")
Label("Favourite", systemImage: "star")
Image(systemName: "star")
}
.buttonStyle(.bordered)
}
.padding()
}
@ViewBuilder
private var buttons: some View {
Button("Save draft") {}
Button("Preview") {}
Button("Publish") {}
.buttonStyle(.borderedProminent)
}
}
#Preview("Narrow") {
ActionsView()
.frame(width: 260)
}
#Preview("Largest text") {
ActionsView()
.dynamicTypeSize(.accessibility2)
}How it works
ViewThatFitsmeasures each child at its ideal size, in order, and shows the first one that fits in the space offered. The last child is used if none fit.in: .horizontalonly checks the width, which is what you want for rows; leave it out to check both directions.- It reacts to everything that changes size: device width, split view, rotation, the guest’s text size and longer translations.
Gotchas
- Only one child is in the view hierarchy at a time, so state inside the children is lost when the choice changes. Keep that state in the parent.
- Children are compared at their ideal size, so views that stretch to fill any space, such as a plain
Coloror a flexible frame, always fit. Order alternatives from largest to smallest and give flexible views a fixed size. - For many items that should wrap onto several lines, a flow layout is a better fit than a list of alternatives.