Toggle in SwiftUI


In this tutorial, you are going to learn about the Toggle control in SwiftUI with the help of some examples.

A SwiftUI Toggle is a control that can move a value between true and false depending on the on or off state of the Toggle switch. Toggle control is used to create a toggle button or switch that can be on or off by the user. The user has to tap it to change its state.

For example, if you want to show some text in the app screen when a toggle switch is on and remove the text when making it off, then the Toggle control can do this job quite easily.

To create a Toggle button, you have to create a Boolean type state variable that stores the value on or off. This boolean property determines if the toggle is off or on.

Now let’s see the example of using the Toggle control in Swift:


    @State var isOn: Bool = true
    
    var body: some View {

        Toggle("Some Setting Option", isOn: $isOn)
            .padding()
        
        Text("Settings set : ")
           + Text(isOn ? "Yes" : "No")
        
        
    }

Below is the app screen for the above SwiftUI code:

SwiftUI Toggle

In our code, we have created a state variable isOn and bind it to our SwiftUI Toggle control. We are also showing “Yes” or “No” text depending upon the value of our state variable isOn.

Now when our toggle button is on, then the value of isOn is true and thus it shows “Yes”. If we off the toggle button, it will then show the text “No”. You can try it by yourself by tapping it.

In our case, the default value of isOn is true, so by default, the Toggle control is in on state. If you want the default state of the toggle switch to off, you can do it by providing the default value of the state variable to false as you can see below:

@State var isOn: Bool = false

Using the if statement to show and hide text with Toggle control

We can also use the if statement to show or hide a text depending upon the Toggle on or off state. Below is given the code that can perform this task:

    @State var showText: Bool = true
    
    var body: some View {

        Toggle("Some Setting Option", isOn: $showText)
            .padding()
        
        if showText {
            Text("Toggle is in on state")
        }
        
        
    }

In this case, the name of our state variable showText binds to the Toggle control.

Now if a user taps the toggle switch, it will remove the text Toggle is in on state as the state of the toggle button become false. Again making it on will show the text.