How it works
ButtonToggleStyle is the toggle style that renders a Toggle as a single button, which appears pressed (filled) when the toggle is on and unpressed (bordered) when it is off. Reach for it when an on/off control reads more naturally as a tappable, state-bearing button than as a switch or checkbox — for example a "Favorite" or "Bold" affordance in a toolbar or inline next to its label. You rarely name the type directly: SwiftUI exposes it through the .button shorthand you pass to the toggleStyle(_:) modifier, and the toggle's own label becomes the button's content.
Apply the style with toggleStyle(.button)
The
toggleStyle(_:)view modifier selects how aToggledraws itself; passing the.buttonvalue installs aButtonToggleStyle. In the example,.toggleStyle(.button)turns theToggle(isOn: $isStarred)into a button that togglesisStarredeach time it's tapped, swapping between its on and off appearances.Supply content through the toggle's label
ButtonToggleStylereuses the closure you give toToggleas the button's label, so whatever view describes the toggle becomes the button's face. Here theLabel("Favorite", systemImage: "star")provides the star icon and text that fill the button, and they remain the button's content in both the on and off states.Read the on/off state from the binding
The style derives its pressed-versus-unpressed look from the
Boolbinding driving the toggle — when the value istruethe button shows its filled, active treatment. The@State private var isStarredbacking theisOn: $isStarredbinding is what the button reflects, so the appearance changes as that state flips.Color the selected state with tint(_:)
A button-styled toggle adopts the surrounding tint for its filled, on-state fill, letting you signal meaning without a custom style. Adding
.tint(.yellow)here makes the button render in yellow onceisStarredbecomestrue, matching the "star" semantics of the label.
@State private var isStarred = false to = true and the button starts in its filled, yellow on-state instead of the bordered off-state.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct ButtonToggleStyleDemo: View {
@State private var isStarred = false
var body: some View {
Toggle(isOn: $isStarred) {
Label("Favorite", systemImage: "star")
}
.toggleStyle(.button)
.tint(.yellow)
.padding()
}
}