Updated for Xcode 14.0 beta 1
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 In-app subscriptions are a pain. The code can be hard to write, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.