The SwiftUI framework comes with a built-in checkbox, but it’s only available on the macOS platform. If you want to use checkboxes on iOS, you have to build your own component. Previously, we’ve covered ToggleStyle
to create custom toggles. By applying the same technique, it’s not hard to build a checkbox for your iOS projects.
Using Checkbox on macOS
Let’s first take a look how you use checkbox on macOS. To create a checkbox, you create a Toggle
view and change it to the .checkbox
style. Here is an example:
struct ContentView: View {
@State private var isChecked = false
var body: some View {
VStack {
Toggle(isOn: $isChecked) {
Text("Buy a pack of Airtags")
}
.toggleStyle(.checkbox)
}
.padding()
}
}
If you run the code on macOS, it renders a standard checkbox.
Creating Checkbox Toggle Style on iOS
The .checkbox
style doesn’t come with the iOS SDK. That said, it’s pretty easy to create this type of toggle style using the ToggleStyle
protocol. If you want to know how to work with ToggleStyle
, please check out our previous tutorial.
On iOS, we can create a new style named CheckboxToggleStyle
which adopts the ToggleStyle
protocol and implement the required method:
struct CheckboxToggleStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
RoundedRectangle(cornerRadius: 5.0)
.stroke(lineWidth: 2)
.frame(width: 25, height: 25)
.cornerRadius(5.0)
.overlay {
Image(systemName: configuration.isOn ? "checkmark" : "")
}
.onTapGesture {
withAnimation(.spring()) {
configuration.isOn.toggle()
}
}
configuration.label
}
}
}
In the makebody
method, we used a RoundedRectangle
view and overlay it with a “checkmark” image when the toggle is enabled.
To use this toggle style, you simply attach the toggleStyle
modifier and pass an instance of CheckboxToggleStyle
like this:
Toggle(isOn: $isChecked) {
Text("Buy a pack of Airtags")
}
.toggleStyle(CheckboxToggleStyle())
If you want to use the dot-syntax, you can extend ToggleStyle
and declare a corresponding static variable like this:
extension ToggleStyle where Self == CheckboxToggleStyle {
static var checkmark: CheckboxToggleStyle { CheckboxToggleStyle() }
}
Now you can apply the style using the dot syntax.
Toggle(isOn: $isChecked) {
Text("Buy a pack of Airtags")
}
.toggleStyle(.checkmark)