跳转至
Structure

PrimitiveButtonStyleConfiguration

The properties of a button.

Declaration

struct PrimitiveButtonStyleConfiguration

Overview

The PrimitiveButtonStyle definition is very similar to that of ButtonStyle, except that in the case of the former, we pass a PrimitiveButtonStyleConfiguration to the makeBody(configuration:). function. PrimitiveButtonStyleConfiguration comes with the button label as a property, but replaces the isPressed property with a trigger() function.

Here, we create a custom TripleTapOnlyStyle, which has a onTapGesture(count:perform:) added to the label to trigger the button action with three consecutive taps.

struct TripleTapOnlyStyle: PrimitiveButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .onTapGesture(count: 3) { configuration.trigger }
    }
}
We can then apply the custom style to a button using the buttonStyle(_:) view modifier:

struct ContentView: View {
    @State private var showBananas = false

    var body: some View {
        VStack(alignment: .center) {
            Button("Triple tap to toggle bananas") {
                showBananas.toggle()
            }
            .buttonStyle(TripleTapOnlyStyle())

            if showBananas {
                Text("🍌🍌")
            }
        }
    }
}
A gif that reads "Triple tap to toggle bananas" in the center of the screen. When tripple tapped, two banana emojis appear beneath the text view.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Instance Method

trigger() Performs the button's action.


Structure

Label A type-erased label of a button.


Instance Property

label A view that describes the effect of calling the button's action.