Friday, November 29, 2024
HomeiOS DevelopmentEasy methods to Create a Checkbox in SwiftUI Utilizing ToggleStyle

Easy methods to Create a Checkbox in SwiftUI Utilizing ToggleStyle


The SwiftUI framework comes with a built-in checkbox, but it surely’s solely obtainable on the macOS platform. If you wish to use checkboxes on iOS, it’s a must to construct your individual element. Beforehand, we’ve lined ToggleStyle to create customized toggles. By making use of the identical method, it’s not onerous to construct a checkbox to 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 fashion. Right here is an instance:

In the event you run the code on macOS, it renders a regular checkbox.

SwiftUI checkbox for macOS

Creating Checkbox Toggle Type on iOS

The .checkbox fashion doesn’t include the iOS SDK. That mentioned, it’s fairly straightforward to create such a toggle fashion utilizing the ToggleStyle protocol. If you wish to know easy methods to work with ToggleStyle, please try our earlier tutorial.

On iOS, we are able to create a brand new fashion 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 fashion, 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 fashion 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. Observe me at Fb, Twitter and Google+.





Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments