66 - Create a Checkbox in SwiftUI

Checkboxes are a staple of user interfaces, enabling users to select or deselect an option. In SwiftUI, checkboxes are created using the Toggle view. However, it’s not immediately obvious how to customize a Toggle to look like a traditional checkbox. Let’s walk through how to create a checkbox-like toggle in SwiftUI.

Here is a simple code snippet in which we create a checkbox using SwiftUI:

struct ContentView: View {
  // 1. Define a state variable that will hold the state of our checkbox
  @State private var isChecked: Bool = false

  var body: some View {
    // 2. Create a VStack to hold our Toggle view
    VStack {
      // 3. Create the Toggle view
      Toggle(isOn: $isChecked) {
        // 4. Add a label for the Toggle
        Text("I agree to the terms and conditions")
      }
      // 5. Add styling to make it look like a checkbox
      .toggleStyle(CheckboxToggleStyle())
      .padding()
    }
  }
}

// 6. Define a custom toggle style to make our Toggle look like a checkbox
struct CheckboxToggleStyle: ToggleStyle {
  func makeBody(configuration: Self.Configuration) -> some View {
    HStack {
      configuration.label
      Spacer()
      Image(systemName: configuration.isOn ? "checkmark.square" : "square")
        .resizable()
        .frame(width: 24, height: 24)
        .onTapGesture { configuration.isOn.toggle() }
    }
  }
}

Your preview should look like this:

Use the CheckboxToggleStyle modifier to create a checkbox.

Here’s what each part of the code does:

That’s all there is to it! With this knowledge, you should be able to create a checkbox-like toggle in SwiftUI. Happy coding!