Skip to main content

Customizing Toggle with ToggleStyle

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

Customizing Toggle with ToggleStyle 관련

SwiftUI by Example

Back to Home

Customizing Toggle with ToggleStyle | SwiftUI by Example

Customizing Toggle with ToggleStyle

Updated for Xcode 15

SwiftUI gives us the ToggleStyle protocol to customize the way Toggle switches look and work. Any struct that conforms to this protocol must implement a makeBody() method that renders the Toggle however you want it, and you’re giving both the label used for the toggle and an isOn binding that you can flip to adjust the toggle.

Important

When you customize a Toggle switch like this, it’s down to you to flip the on state yourself somehow – SwiftUI will not do it for you.

To demonstrate custom Toggle styles, here’s one that uses a button to flip the on state, then adds a custom label to show that state. Rather than use a moving circle like the standard iOS Toggle, I’ve made this show one of two SF Symbols:

struct CheckToggleStyle: ToggleStyle {
    func makeBody(configuration: Configuration) -> some View {
        Button {
            configuration.isOn.toggle()
        } label: {
            Label {
                configuration.label
            } icon: {
                Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle")
                    .foregroundStyle(configuration.isOn ? Color.accentColor : .secondary)
                    .accessibility(label: Text(configuration.isOn ? "Checked" : "Unchecked"))
                    .imageScale(.large)
            }
        }
        .buttonStyle(.plain)
    }
}

// An example view showing the style in action
struct ContentView: View {
    @State private var isOn = false

    var body: some View {
        Toggle("Switch Me", isOn: $isOn)
            .toggleStyle(CheckToggleStyle())
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
How to create a toggle switch | SwiftUI by Example

How to create a toggle switch
How to hide the label of a Picker, Stepper, Toggle, and more using labelsHidden() | SwiftUI by Example

How to hide the label of a Picker, Stepper, Toggle, and more using labelsHidden()
Customizing Button with ButtonStyle | SwiftUI by Example

Customizing Button with ButtonStyle
Customizing ProgressView with ProgressViewStyle | SwiftUI by Example

Customizing ProgressView with ProgressViewStyle
Two-way bindings in SwiftUI | SwiftUI by Example

Two-way bindings in SwiftUI

이찬희 (MarkiiimarK)
Never Stop Learning.