Toggle in SwiftUI is same as our good old UIKit’s Switch control. Toggle control can turn on or off. Toggle needs a binding variable which updates as you toggle the control view’s state.
Toggle control comes with a label and switch. Let’s start with a simple example. In this example, we will create a State variable called agreeToTerms and initialize it with false value. We will bind this variable to Toggle by passing binding value in isOn parameter. As shown below:
struct ToggleExample: View {
@State private var agreeToTerms = false
var body: some View {
VStack {
Text("DevTechie Terms and Conditions")
Toggle("Agree", isOn: $agreeToTerms)
}
.padding()
}
}
You can observe change on binding variable at other places. For example, let’s say, your app requires users to agree on terms and conditions, in this case toggle on represents that user has agreed to the terms and is ready to move forward. We will observe change in toggle’s binding value and enable/disable continue button based on the state of toggle as shown below:
Toggle can be styled in a few ways, you have option to apply ToggleStyle modifier to apply some of the predefined styles. For example, starting iOS 15+ you can turn your default Toggle switch into a toggle button: