Create a Checkbox in SwiftUI
                
                  Written by Team Kodeco
              
            
          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:
 
    
Here’s what each part of the code does:
- 
@State private var isChecked: Bool = false: This defines a mutable state for our checkbox. When the value of this variable changes, the view will automatically update. The$prefix beforeisCheckedwhen we refer to it in theToggleview is used to bind the state of the checkbox to ourisCheckedstate variable.
- 
VStack: This is a stack that arranges views vertically. In this case, it’s used to hold ourToggleview.
- 
Toggle(isOn: $isChecked): This creates the toggle. TheisOnparameter is a binding to a Boolean that determines whether the toggle is on or off. In this case, we’re binding it to ourisCheckedstate variable.
- 
Text("I agree to the terms and conditions"): This is the label for our toggle. It’s displayed next to the checkbox.
- 
.toggleStyle(CheckboxToggleStyle()): This modifies the toggle style. We’re using a customToggleStylethat we define below to make ourTogglelook like a checkbox.
- 
CheckboxToggleStyle: This is a customToggleStylethat we’re defining. ThemakeBodymethod determines what our toggle looks like. In this case, it’s anHStack(a stack that arranges views horizontally) containing our label and anImage. TheImagechanges based on whether the toggle is on or off, and we’re adding anonTapGestureto it so that it toggles the state when it’s tapped.
That’s all there is to it! With this knowledge, you should be able to create a checkbox-like toggle in SwiftUI. Happy coding!