NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Customizing Toggle with ToggleStyle

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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")
                    .foregroundColor(configuration.isOn ? .accentColor : .secondary)
                    .accessibility(label: Text(configuration.isOn ? "Checked" : "Unchecked"))
                    .imageScale(.large)
            }
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// 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 project

Hacking with Swift is sponsored by Waldo

SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.

Try for free today!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.