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
Boolthat 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
@Stateor@Bindingvariable for the toggle'sisOnbinding, which causes the toggle not to update. - Forgetting to prefix the state variable with
$when passing it toToggle. - 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
Stringor anyViewdescribing 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.