How it works
SwitchToggleStyle is the toggle style that renders a Toggle as the familiar sliding on/off switch found throughout iOS settings. It conforms to ToggleStyle, so SwiftUI uses it to draw the control and to wire up the user's taps to the toggle's Boolean binding. Reach for it when you want to guarantee the switch presentation regardless of platform defaults, or when you want to recolor the switch's filled track. On the platforms where a Toggle already defaults to a switch, the main reason to name this style explicitly is to set that tint.
Apply the style with toggleStyle(_:)
A toggle style takes effect through the
toggleStyle(_:)modifier, which sets the style for every Toggle in the view hierarchy beneath it. Here it is attached to the enclosingForm, so both theWi-FiandBluetoothtoggles adopt the switch presentation from a single call:.toggleStyle(SwitchToggleStyle(tint: .green)).Tint the switch with init(tint:)
The
init(tint:)initializer takes aColorused to fill the switch track when it is in the on position. Passing.greenmakes every switch beneath the modifier glow green when enabled, overriding the system accent color; passingnilfalls back to the default tint.Drive each switch with an isOn binding
SwitchToggleStyle only governs appearance and interaction — the state still lives in the Toggle's
isOnbinding. The$wifiand$bluetoothbindings to the@Stateproperties are what flip when the user drags or taps the switch, so the style turns those Boolean values into a directly manipulable control.Rely on the ToggleStyle conformance
Because SwitchToggleStyle conforms to
ToggleStyle, it is interchangeable with other styles such as.buttonor.checkboxwherevertoggleStyle(_:)is accepted. That conformance is what lets you swap the presentation of the sameToggle("Wi-Fi", isOn: $wifi)declaration without touching its label or binding.
SwitchToggleStyle(tint: .green) to SwitchToggleStyle(tint: .red) and toggle Wi-Fi on to watch the filled switch track switch from green to red.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 SwitchToggleStyleDemo: View {
@State private var wifi = true
@State private var bluetooth = false
var body: some View {
Form {
Toggle("Wi-Fi", isOn: $wifi)
Toggle("Bluetooth", isOn: $bluetooth)
}
.toggleStyle(SwitchToggleStyle(tint: .green))
.padding()
}
}