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.
toggleStyle
modifier to customize ToggleThe 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:
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)
.padding()
.toggleStyle(SwitchToggleStyle(tint: .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.
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)
.padding()
.toggleStyle(.button)
We can also change the color of the button toggle using tint
modifier:
Toggle("Some Setting Option", isOn: $isOn)
.padding()
.toggleStyle(.button)
.tint(.green)
ToggleStyle
protocol to customize ToggleSwiftUI 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 {
configuration.label
Spacer()
Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle")
.resizable()
.frame(width: 26, height: 26)
.foregroundColor(configuration.isOn ? .green : .gray)
.onTapGesture {
configuration.isOn.toggle()
}
}
}
}
Now use the struct in toggleStyle
modifier of our toggle:
Toggle("Some Setting Option", isOn: $isOn)
.padding()
.toggleStyle(CheckboxToggleStyle())
It will now work as you can see below: