How one can Create a Checkbox in SwiftUI Utilizing ToggleStyle


The SwiftUI framework comes with a built-in checkbox, nevertheless it’s solely accessible on the macOS platform. If you wish to use checkboxes on iOS, it’s a must to construct your individual part. Beforehand, we’ve coated ToggleStyle to create customized toggles. By making use of the identical method, it’s not laborious to construct a checkbox on your iOS initiatives.

Utilizing Checkbox on macOS

Let’s first have a look how you utilize checkbox on macOS. To create a checkbox, you create a Toggle view and alter it to the .checkbox type. Right here is an instance:

In case you run the code on macOS, it renders a typical checkbox.

SwiftUI checkbox for macOS

Creating Checkbox Toggle Model on iOS

The .checkbox type doesn’t include the iOS SDK. That mentioned, it’s fairly straightforward to create this sort of toggle type utilizing the ToggleStyle protocol. If you wish to know find out how to work with ToggleStyle, please try our earlier tutorial.

On iOS, we will create a brand new type named CheckboxToggleStyle which adopts the ToggleStyle protocol and implement the required methodology:

Within the makebody methodology, we used a RoundedRectangle view and overlay it with a “checkmark” picture when the toggle is enabled.

swiftui-ios-checkbox

To make use of this toggle type, you merely connect the toggleStyle modifier and go an occasion of CheckboxToggleStyle like this:

If you wish to use the dot-syntax, you may lengthen ToggleStyle and declare a corresponding static variable like this:

Now you may apply the type utilizing the dot syntax.


Founding father of AppCoda. Creator of a number of iOS programming books together with Starting iOS Programming with Swift and Mastering SwiftUI. iOS App Developer and Blogger. Comply with me at Fb, Twitter and Google+.



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles