Member-only story

Crafting SwiftUI Custom Checkboxes for User Agreements

This can work

--

Photo by Thomas Bormans on Unsplash

This article uses code from my simple design library system. Take a look at https://github.com/stevencurtis/DesignLibrary/tree/main to see how that works.

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 15.0, and Swift 5.9

Terminology:

SwiftUI: A modern way to declare user interfaces for any Apple device in Swift.

Binding: A SwiftUI property wrapper that connects a property to a source of truth, allowing for interactive updates.

ObservableObject: A type of object with a publisher that emits before the object has changed, used in SwiftUI to manage model data.

Background

In many applications, especially those involving legal agreements, it’s common to present users with terms and conditions that they must agree to before proceeding. Typically, this involves checkboxes that users must tap to indicate acceptance. Traditionally, this could become cumbersome with UIKit, but SwiftUI simplifies this process significantly, enhancing both developer and user experience.

Creating a reusable and visually appealing checkbox component in SwiftUI not only streamlines code but also aligns with modern UI practices. Here’s how to enhance your SwiftUI views with custom checkboxes.

There are two versions of this code, one that uses the new observable macro and one that uses ObservableObject. To maximise how easy this is to read I’ll cover the ObservableObject version first and then copy-paste the observable macro version below it. I hope this helps everyone out!

Implementation

Implement the checkbox view

Here I start with the CheckboxView component in SwiftUI. This view manages the image and allows the user to click it and the component reacts as expected.

struct CheckboxView: View {
@Binding var isChecked: Bool
let label: String

var body: some View {
HStack {
Text(label)
Image(systemName: isChecked ? "checkmark.square.fill" : "square")…

--

--

No responses yet