How it works
ToggleStyle is the protocol that defines the appearance and interaction behavior of every Toggle in your interface. Rather than hard-coding how an on/off control looks, you select or implement a style and let SwiftUI render the toggle's label and binding state accordingly. Reach for ToggleStyle when the default presentation isn't right for a context — for example when a toggle belongs inline next to other controls, reads better as a pressable button, or needs a custom look that matches your design.
Apply a style with toggleStyle(_:)
You don't conform to
ToggleStyledirectly to use it; you pass a conforming style to the.toggleStyle(_:)modifier on aToggle(or on a container of toggles, which propagates the style through the environment). In the example,.toggleStyle(.switch)is attached to the Wi-FiToggleand.toggleStyle(.button)to the Bluetooth one, so each control adopts its own presentation while sharing the sameisOnsemantics.Choose a built-in style value
SwiftUI ships several standard styles exposed as static members, so you write a leading-dot value instead of constructing a type.
.switchproduces the familiar sliding switch, and.buttonrenders the toggle as a control that highlights when its bound value is on. Both areToggleStylevalues that satisfy the modifier's parameter.Drive the style from the toggle's binding
Whatever style is applied, it reflects and mutates the same
Boolbinding theTogglewas created with. Here$wifiOnand$bluetoothOn(backed by@State) supply that binding, so the.switchand.buttonstyles each draw their on/off appearance from the current state and flip it on interaction.Use the label the toggle provides
A
ToggleStyleis responsible for laying out the toggle's label alongside its control affordance, so the title you give theToggleflows into the chosen style automatically. The strings"Wi-Fi"and"Bluetooth"become the labels that the switch and button styles position and render.
.toggleStyle(.switch) on the Wi-Fi toggle to .toggleStyle(.button) and watch the same $wifiOn state render as a pressable, highlighting control instead of a sliding switch.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 ToggleStyleDemo: View {
@State private var wifiOn = true
@State private var bluetoothOn = false
var body: some View {
VStack(spacing: 20) {
Toggle("Wi-Fi", isOn: $wifiOn)
.toggleStyle(.switch)
Toggle("Bluetooth", isOn: $bluetoothOn)
.toggleStyle(.button)
}
.padding()
}
}