0
0
Ios-swiftHow-ToBeginner ยท 3 min read

How to Use Toggle in SwiftUI: Simple Guide with Examples

In SwiftUI, use the Toggle view to create a switch that users can turn on or off. Bind it to a @State Boolean variable to track its value and update your UI automatically.
๐Ÿ“

Syntax

The Toggle view requires a binding to a Boolean state and a label to describe the toggle's purpose.

  • isOn: A binding to a Bool that controls the toggle state.
  • label: A view that describes what the toggle controls.
swift
Toggle("Label Text", isOn: $stateVariable)
๐Ÿ’ป

Example

This example shows a toggle that controls whether a message is visible. The toggle updates the isOn state, and the text appears or disappears accordingly.

swift
import SwiftUI

struct ContentView: View {
  @State private var isOn = false

  var body: some View {
    VStack {
      Toggle("Show Message", isOn: $isOn)
        .padding()
      if isOn {
        Text("Hello, SwiftUI Toggle!")
          .font(.headline)
          .foregroundColor(.blue)
      }
    }
    .padding()
  }
}
Output
A toggle switch labeled 'Show Message' and when switched on, the text 'Hello, SwiftUI Toggle!' appears below it.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Not using a @State or @Binding variable for the toggle's isOn binding, which causes the toggle not to update.
  • Forgetting to prefix the state variable with $ when passing it to Toggle.
  • Using a constant Boolean instead of a binding, which makes the toggle read-only.
swift
struct WrongToggleView: View {
  let isOn = false

  var body: some View {
    // This will not work because isOn is not a binding
    Toggle("Wrong Toggle", isOn: isOn)
  }
}

struct CorrectToggleView: View {
  @State private var isOn = false

  var body: some View {
    Toggle("Correct Toggle", isOn: $isOn)
  }
}
๐Ÿ“Š

Quick Reference

  • Toggle(label, isOn: $state): Creates a toggle switch bound to a Boolean state.
  • @State: Use to declare a mutable state variable for toggle binding.
  • $: Prefix to pass a binding of the state variable.
  • Label: Can be a String or any View describing the toggle.
โœ…

Key Takeaways

Use Toggle with a binding to a @State Boolean variable to track on/off state.
Always prefix the state variable with $ when passing it to Toggle.
The toggle label can be a simple string or a custom view for better UI.
Avoid using constant Booleans for isOn as it disables toggle interaction.
Toggle automatically updates the UI when the bound state changes.