SwiftUI

How to Create a Checkbox in SwiftUI Using ToggleStyle


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:

If you run the code on macOS, it renders a standard checkbox.

SwiftUI checkbox for macOS

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:

In the makebody method, we used a RoundedRectangle view and overlay it with a “checkmark” image when the toggle is enabled.

swiftui-ios-checkbox

To use this toggle style, you simply attach the toggleStyle modifier and pass an instance of CheckboxToggleStyle like this:

If you want to use the dot-syntax, you can extend ToggleStyle and declare a corresponding static variable like this:

Now you can apply the style using the dot syntax.

Tutorial
Advanced Unit Testing in Swift Using Swinject, Quick and Nimble
Tutorial
Building a Simple ARKit Demo with SceneKit in Swift 4 and Xcode 9
iOS
Swift DocC: How to Host Document Archive on Web Server and GitHub Pages
Shares