Contents

buttonSizing(_:)

The preferred sizing behavior of buttons in the view hierarchy.

Declaration

nonisolated func buttonSizing(_ sizing: ButtonSizing) -> some View

Parameters

  • sizing:

    A button sizing behavior that may be used to influence the primary axis size of buttons capable of adapting to it.

Discussion

Views may use the specified button sizing when determining the size they choose to be in their primary axis within their parent view’s proposed size.

Many built-in controls that display as a button adapt to this view modifier. For example, you can make certain styles of Button, Picker, ControlGroup, and Toggle flexible by applying this modifier to them or their container.

This example creates a button that spans the width of its container, which you may want to do if the button is placed in a narrow context, like the sidebar of a welcome window.

Button("Open Document…", action: openDocument)
    .buttonSizing(.flexible)

Your own views and styles can adapt to this view modifier by reading the buttonSizing environment value and applying an appropriate frame.

struct CustomButtonStyle: ButtonStyle {
    @Environment(\.buttonSizing) private var buttonSizing

    private var maxWidth: CGFloat {
        switch buttonSizing {
        case .flexible: .infinity
        case .fitted, _: nil
        }
    }

    func makeBody(configuration: Configuration) -> some View {
        configuration.content
            .frame(maxWidth: maxWidth)
            .background(.tint, in: Capsule())
    }
}