TechnologiesSwiftUI

SwitchToggleStyle struct

iOSmacOStvOSwatchOSvisionOSiOS 13.0+✓ renders

A toggle style that displays a leading label and a trailing switch.

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.

  1. 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 enclosing Form, so both the Wi-Fi and Bluetooth toggles adopt the switch presentation from a single call: .toggleStyle(SwitchToggleStyle(tint: .green)).

  2. Tint the switch with init(tint:)

    The init(tint:) initializer takes a Color used to fill the switch track when it is in the on position. Passing .green makes every switch beneath the modifier glow green when enabled, overriding the system accent color; passing nil falls back to the default tint.

  3. Drive each switch with an isOn binding

    SwitchToggleStyle only governs appearance and interaction — the state still lives in the Toggle's isOn binding. The $wifi and $bluetooth bindings to the @State properties are what flip when the user drags or taps the switch, so the style turns those Boolean values into a directly manipulable control.

  4. Rely on the ToggleStyle conformance

    Because SwitchToggleStyle conforms to ToggleStyle, it is interchangeable with other styles such as .button or .checkbox wherever toggleStyle(_:) is accepted. That conformance is what lets you swap the presentation of the same Toggle("Wi-Fi", isOn: $wifi) declaration without touching its label or binding.

Try it — Change 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.

SwitchToggleStyle.swift
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()
    }
}
Live preview
Wi-Fi Bluetooth
Wi-Fi Bluetooth
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →