HomeiOS DevelopmentThe right way to Create a Checkbox in SwiftUI Utilizing ToggleStyle

The right way to 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 lined ToggleStyle to create customized toggles. By making use of the identical method, it’s not onerous to construct a checkbox on your iOS tasks.

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 the event you run the code on macOS, it renders an ordinary 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 kind of toggle type utilizing the ToggleStyle protocol. If you wish to know how one can work with ToggleStyle, please take a look at our earlier tutorial.

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

Within the makebody technique, 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’ll be able to prolong ToggleStyle and declare a corresponding static variable like this:

Now you’ll be able to apply the type utilizing the dot syntax.


Founding father of AppCoda. Writer 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

Most Popular

Recent Comments