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.

ActionsView.swift
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

Gotchas