49 - Create a Toggle Button in SwiftUI

Toggle buttons are integral components in many user interfaces, allowing users to switch between two states, often representing an on/off or true/false choice. SwiftUI, with its declarative syntax, makes creating such interactive elements incredibly straightforward. Let’s dive in and learn how to create a toggle button using SwiftUI.

In SwiftUI, a Toggle is a UI control that can be turned on (true) or off (false). It binds to a variable in your code that represents its current state. To create and customize a toggle, consider the following code snippet:

struct ContentView: View {
  @State private var isOn = false

  var body: some View {
    Toggle(isOn: $isOn) {
      Text("Switch state")
    }
    .toggleStyle(.switch)
    .padding()
  }
}

Your preview should look like this:

Use the Toggle view to create a toggle control.

Here’s what this code is doing:

Modifying the Appearance of a Toggle

In SwiftUI, you can modify the appearance of a Toggle view by using the .toggleStyle() modifier. The built-in toggle styles in SwiftUI include:

In addition to these built-in styles, you can also create your own custom toggle styles by conforming to the ToggleStyle protocol. This gives you full control over the toggle’s appearance and interaction.

So, there you have it! That’s how to create a toggle button in SwiftUI. Always remember that the key is to bind your Toggle to a @State variable. SwiftUI will take care of the rest, re-rendering your UI whenever the state changes. Happy toggling!