Customize the look and feel of SwiftUI Toggle

Previously I published a tutorial on SwiftUI Toogle control for the understanding of how to use it. This time, you will learn how to customize the look and feel of the SwiftUI Toggle with the help of appropriate examples and corresponding results.

In order to customize the Toggle switch, there are two options available. One is by using the toggleStyle modifier and the other one is by using the ToggleStyle protocol. Both the modifier and protocol have the same name.

Using toggleStyle modifier to customize Toggle

The toggleStyle modifier can set the style for a SwiftUI Toggle in a view hierarchy. Using this modifier, we can customize the look and feel of the toggle switch in a number of ways. Below is given some of them:

Change the Switch color of Toggle

Below is given the code to show you how to use the toggleStyle modifier to change the color of the toggle switch:

        Toggle("Some Setting Option", isOn: $isOn)
            .toggleStyle(SwitchToggleStyle(tint: .purple))
SwiftUI Toggle color purple

in the above example, we change the color of our toggle switch. We provide the tint color to purple. Here the SwitchToggleStyle struct has been used for this task. The SwitchToggleStyle is the built-in style of a toggle.

Convert the toggle switch into a button

We can also replace the toggle switch complete with a button. Don’t worry, you don’t need to create a button or write new code for this. Just providing .button the modifier will do the job. Below is how to do this:

        Toggle("Some Setting Option", isOn: $isOn)
Button Toggle

We can also change the color of the button toggle using tint modifier:

        Toggle("Some Setting Option", isOn: $isOn)
Green Button Toggle

Use ToggleStyle protocol to customize Toggle

SwiftUI provides the ToggleStyle protocol to allow iOS or Apple developers to customize the way Toggle switches look and work. Using this protocol, you can fully customize the appearance of the toggle switch.

For example, you can completely change the toggle switch and convert it to a checkbox. For this, you have to create a new struct that conforms to the ToggleStyle protocol:

struct CheckboxToggleStyle: ToggleStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        return HStack {
            Image(systemName: configuration.isOn ? "" : "circle")
                .frame(width: 26, height: 26)
                .foregroundColor(configuration.isOn ? .green : .gray)
                .onTapGesture {

Now use the struct in toggleStyle modifier of our toggle:

        Toggle("Some Setting Option", isOn: $isOn)

It will now work as you can see below:

Checkbox in SwiftUI