跳转至
Structure

Toggle

An on-off switch.

Declaration

struct Toggle<Label> : View where Label : View

Overview

Create a toggle by providing an isOn binding and a label.

struct SwitchView: View {
    @State private var vibrateOnRing = false

    var body: some View {
        Toggle(isOn: $vibrateOnRing) {
            Text("Vibrate on Ring")
        }
    }
}
A screenshot displaying a toggle reading "Vibrate on Ring" which is switched to off.

For the common case of text-only labels, you can use the convenience initializer that takes a title string (or localized string key) as its first parameter, instead of a trailing closure:

struct SwitchView: View {
    @State private var vibrateOnRing = true

    var body: some View {
        Toggle("Vibrate on Ring", isOn: $vibrateOnRing)
    }
}
A screenshot displaying a toggle reading "Vibrate on Ring" which is switched to on.

Styling Toggles

You can customize the appearance of toggles by using a ToggleStyle, or creating your own styles that conform to the ToggleStyle protocol. Available styles include:

To set the style, use the toggleStyle(_:) modifier:

struct RingerView: View {
    @State private var vibrateOnRing = true
    @State private var vibrateOnSilent = true

    var body: some View {
        VStack {
            Toggle("Vibrate on Ring 🔔", isOn: $vibrateOnRing)
            Toggle("Vibrate on Silent 🔕", isOn: $vibrateOnSilent)
        }
        .toggleStyle(SwitchToggleStyle(tint: .orange))
    }
}
A gif displaying two toggles in a VStack reading "Vibrate on Ring" and "Vibrate on Silent" with an orange tint color being switched on and off; the tint is applied using SwitchToggleStyle.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Type Alias

Body The type of view representing the body of this view.


Instance Property

body The content and behavior of the view.


Initializer

init(_:) Creates a an on-off switch based on a toggle style configuration.

init(_:isOn:) Creates an on-off switch with a localized string key label.

init(_:isOn:) Creates an on-off switch with a string label.

init(isOn:label:) Creates an on-off switch with a custom label.