iOS Development

How you can Create a Checkbox in SwiftUI Utilizing ToggleStyle

How you can Create a Checkbox in SwiftUI Utilizing ToggleStyle
Written by admin


The SwiftUI framework comes with a built-in checkbox, however it’s solely accessible on the macOS platform. If you wish to use checkboxes on iOS, it’s a must to construct your personal element. Beforehand, we’ve coated ToggleStyle to create customized toggles. By making use of the identical approach, it’s not onerous 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:

If you happen to 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 you can 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 move an occasion of CheckboxToggleStyle like this:

If you wish to use the dot-syntax, you’ll be able to lengthen 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. 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+.



About the author

admin

Leave a Comment