Stack SwiftUI Buttons When Equal Widths Stop Fitting

Two export buttons look tidy side by side. Then “Export CSV” becomes “Export spreadsheet,” someone increases their text size, and one label starts negotiating for custody of the other button’s space.

We can give both buttons equal widths while their labels fit comfortably, then stack them when they need more room. The decision should come from the available width and the actual button sizes, including their styling—not an assumed phone width.

This Stack Overflow question describes the exact difficulty. It already has an accepted answer using ViewThatFits and shared label footprints. Here we’ll take another route: one small custom layout that measures its children directly and keeps the same button views in both arrangements.

Natalia Panferova’s recent explanation of fixedSize is useful background. Fixing a view’s size changes what it asks for; it doesn’t manufacture more room. Our container needs to respond to that request.

This example uses Layout, available from iOS 16. The technique is established; the November 2026 toolchain and runtime checks are described below.

Save draft and Publish report buttons with equal widths, arranged side by side. The same Save draft and Publish report buttons stacked vertically at a narrower width.
Actual simulator captures from the test screen: 360 points of available width, then 180 points, with the same text size.

Make the breakpoint a measurement

A button’s ideal width is the width it chooses when the parent leaves that dimension unspecified. We ask the styled button, so its padding is included.

For two equal-width buttons, adding their individual ideal widths isn’t enough. Both slots must accommodate the wider button:

Required row width = widest ideal button width × button count + spacing between buttons.

If the row fits, split the available width equally. Otherwise, give each button the full width and put it below the previous one.

There’s a second measurement after that decision. A button measured at its ideal width can be short; the same button constrained to a narrow column can need several lines. Using its earlier height would undo the whole exercise.

Add this layout to a Swift file:

import SwiftUI

struct AdaptiveActionLayout: Layout {
    private let spacing: CGFloat = 12

    private struct Arrangement {
        var size: CGSize
        var childWidth: CGFloat
        var heights: [CGFloat]
        var isRow: Bool
    }

    private func arrangement(
        width proposedWidth: CGFloat?,
        subviews: Subviews
    ) -> Arrangement {
        guard !subviews.isEmpty else {
            return Arrangement(size: .zero, childWidth: 0, heights: [], isRow: true)
        }

        let widest = subviews.map { $0.sizeThatFits(.unspecified).width }.max() ?? 0
        let gaps = spacing * CGFloat(subviews.count - 1)
        let idealRowWidth = widest * CGFloat(subviews.count) + gaps
        let width = proposedWidth.flatMap { $0.isFinite ? max(0, $0) : nil }
            ?? idealRowWidth
        let isRow = idealRowWidth <= width
        let childWidth = isRow ? (width - gaps) / CGFloat(subviews.count) : width
        let heights = subviews.map {
            $0.sizeThatFits(ProposedViewSize(width: childWidth, height: nil)).height
        }
        let height = isRow ? (heights.max() ?? 0) : heights.reduce(0, +) + gaps

        return Arrangement(
            size: CGSize(width: width, height: height),
            childWidth: childWidth,
            heights: heights,
            isRow: isRow
        )
    }

    func sizeThatFits(
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout ()
    ) -> CGSize {
        var size = arrangement(width: proposal.width, subviews: subviews).size
        if proposal.width == .infinity, !subviews.isEmpty {
            size.width = .infinity
        }
        return size
    }

    func placeSubviews(
        in bounds: CGRect,
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout ()
    ) {
        let plan = arrangement(width: bounds.width, subviews: subviews)
        var x = bounds.minX
        var y = bounds.minY

        for (index, subview) in subviews.enumerated() {
            let height = plan.isRow ? plan.size.height : plan.heights[index]
            subview.place(
                at: CGPoint(x: x + plan.childWidth / 2, y: y + height / 2),
                anchor: .center,
                proposal: ProposedViewSize(width: plan.childWidth, height: height)
            )
            if plan.isRow {
                x += plan.childWidth + spacing
            } else {
                y += height + spacing
            }
        }
    }
}

The first pass uses .unspecified to ask for each child’s ideal size. The second proposes the chosen width and leaves height unspecified, so wrapping contributes to the height we return.

SwiftUI can also probe the layout’s flexibility. An infinite-width proposal asks for its maximum width, so we report .infinity for that probe. It is separate from the finite bounds used to position buttons.

sizeThatFits reports the result. placeSubviews repeats the calculation using the bounds actually assigned by the parent. Placement starts at bounds.minX and bounds.minY; custom layout bounds are not guaranteed to begin at zero.

There is deliberately no manual right-to-left reversal. SwiftUI mirrors the layout’s x positions for right-to-left presentation. Reversing them ourselves would mirror twice. Apple explains both details in Compose custom layouts with SwiftUI.

For a small action group, recalculating these measurements is straightforward. There’s no geometry preference, state update, or second view hierarchy to coordinate.

Let the labels use the space

Put this view in the same file. Present ExportActionsDemo() from your app to try it; the actions select a format rather than performing an export.

struct ExportActionsDemo: View {
    @State private var selection = "Choose an export format."

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                Text("Export your report")
                    .font(.title2)

                AdaptiveActionLayout {
                    Button {
                        selection = "PDF selected."
                    } label: {
                        actionLabel("Export PDF")
                    }
                    .buttonStyle(.borderedProminent)

                    Button {
                        selection = "Spreadsheet selected."
                    } label: {
                        actionLabel("Export spreadsheet")
                    }
                    .buttonStyle(.bordered)
                }

                Text(selection)
            }
            .padding()
        }
    }

    private func actionLabel(_ title: LocalizedStringKey) -> some View {
        Text(title)
            .fixedSize(horizontal: false, vertical: true)
            .frame(maxWidth: .infinity, minHeight: 44)
    }
}

The label’s .frame(maxWidth: .infinity) lets it occupy the width the layout proposes. Its minimum height gives both actions a consistent 44-point floor before the native button style adds its own padding. The primary action gets visual emphasis through .borderedProminent, while the secondary action retains the same minimum label height.

fixedSize(horizontal: false, vertical: true) leaves the label’s width flexible while letting its height follow the wrapped text. Avoid fixing the horizontal axis here: a long label must still wrap when even a full-width button is too narrow.

The surrounding ScrollView matters too. At large text sizes, the correct answer may simply be more vertical content. A fixed-height parent that clips the result would bring the original problem back from a different direction.

Both buttons remain children of the same layout. Changing the arrangement changes their positions, rather than choosing between separate copies inside an HStack and a VStack. This is the same identity concern discussed in keeping keyboard focus stable when forms reflow, applied here to a content-driven action group.

Keep the policy small

ViewThatFits is still a good choice when you have several alternative presentations. It picks the first candidate whose ideal size fits on the constrained axes. You don’t need a custom layout for every adaptive screen.

This one earns its place when equal widths and direct measurement of the same children are the requirements. It has a few deliberate limits:

  • It suits a small group of flexible text buttons. A child with a fixed width or a custom style that refuses the proposed width can still overflow; a layout proposal is not a clipping rule.
  • It chooses one row or one column. It does not pack buttons into multiple partial rows. For tags and filters, use the wrapping chip layout.
  • Explicit line breaks remain line breaks. “Ideal width” does not mean this container strips newlines or guarantees one line for every possible label.
  • It needs a finite assigned width to make a useful wrapping decision. An unspecified width asks for the natural equal-width row. An infinite width is a maximum-size probe, so sizeThatFits reports horizontal flexibility. A horizontal scroll view still won’t give this layout the screen-width constraint it needs.

The 12-point spacing is a local design choice. Keep the implementation focused unless your app actually needs per-pair spacing preferences, baseline alignment, or another arrangement policy.

Check the transition, not just the preview

The useful checks are behavioral:

ChangeExpected result
Reduce the available widthBoth buttons move into a column and retain equal widths
Increase Dynamic TypeLabels get room to grow instead of a smaller font or an ellipsis
Use longer translated labelsRecalculate from those labels; don’t reuse an English breakpoint
Switch to right-to-left layoutMirror the row; retain the column’s top-to-bottom order
Move between row and columnExisting child state survives and each action still works

The downloadable sample includes the complete example and a separate test screen with width, text-size, long-label, and right-to-left fixtures.

Verification: the exact two code blocks compile with Xcode 27.2 and Swift 6.4.2, using an iOS 16 minimum target and Swift 6 language mode, with ordinary and MainActor default isolation. Native UI tests on an iPhone 18 Pro simulator running iOS 27.2 exercise the example’s actions, equal widths, 44-point minimum heights, wrapping, largest accessibility text size, right-to-left placement, and child state across reflow. Screenshots check the visible labels as well as the measured frames. This is not an iOS 16 runtime or physical-device result, and it does not establish VoiceOver focus behavior.

Give the labels a chance to tell you how much room they need. When the row stops fitting, moving a button down is usually kinder than making its words disappear.