Swift and SwiftUI tutorials for Swift Developers

How to create a Toggle Switch & Button in SwiftUI

In this tutorial we will see how to create a toggle switch and a toggle button in SwiftUI. A toggle has only two states: ON and OFF (true and false). This control is useful for making users select between two options.

Similarly to how to create a Picker control, we need to declare a state variable to store the current configuration of the toggle.

Let’s start by declaring the state variable:

@State private var showPhones = false

To create a toggle switch we use the following code:

Toggle(isOn: $showPhones {

Text("Show Phones Only")

}

You use the Toggle view to create a toggle switch and pass the current state of the toggle. In the closure you present the description of the toggle. Here we simply use a text view.

The XCode canvas would now have to present a toggle switch. The showPhones variable will always keep track of the user’s selection.

The result in XCode would be the following:

Another way to initialize a toggle is as follows with an SF Symbol, for example:

Toggle("Wi-Fi", systemImage: "wifi", isOn: $showPhones)

Which in XCode results in:

We use a SF Symbol to create the toggle.

Customizing Toggle Switch Color

In SwiftUI we can customize the toggle color with the .tint modifier as follows:

Toggle("Wi-Fi", systemImage: "wifi", isOn: $showPhones)
.tint(.blue)

In XCode the result would be the following:

How to create a Toggle Button in SwiftUI

A toggle button is a component in many UIs, allowing users to switch between two states representing ON/OFF or true/false. SwiftUI, with its declarative syntax, makes creating these interactive elements incredibly easy.

We’ll need a state variable to hold the true or false value. To create and customize a toggle button, consider the following code:

Toggle("Wi-Fi", systemImage: showPhones ? "wifi" : "wifi.slash", isOn: $showPhones)
                            .font(.largeTitle)
                            .tint(.blue)
                            .toggleStyle(.button)
                            .labelStyle(.iconOnly)

Which would result in XCode:

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to create a Picker in SwiftUI

Next Article

How to create a Stepper in SwiftUI

Related Posts