< Customizing ProgressView with ProgressViewStyle | How to change the background color of List, TextEditor, and more > |
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
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.