Today I will show you how to use Toggle.
The use of Toggle controls is very common. For example, the Bluetooth and Airplane mode switches in iPhone settings.
Steps:
First, add a property of type Bool and set its initial value to true
This property has a @State property wrapper, indicating that the property will be data-bound to the Toggle control.
@State var isToggleOn = true
Next:
Add another Text view via the extension method.
This Text view is used for displaying the value of the Bool property.
Set the font color of the Text view to green and bold.
Text("Show Toggle: ")
+ Text("\(isToggleOn.description)")
.foregroundColor(.green)
.bold()
Next:
Add a Toggle control and bind its Bool property.
When the user adjusts the Toggle control, the value of this property will also change synchronously.
Toggle(isOn: $isToggleOn) {
Text("Show Toggle")
}
Source Code:
struct ContentView: View {
@State var isToggleOn = true
var body: some View {
VStack {
Text("Show Toggle: ")
+ Text("\(isToggleOn.description)")
.foregroundColor(.green)
.bold()
Toggle(isOn: $isToggleOn) {
Text("Show Toggle")
}
.padding()
}
}
}
Follow me on:
Comments