Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Segmented Control in SwiftUI
Written by Team Kodeco

A segmented control displays a set of segments, each of which functions as a button. When the user touches a segment, it becomes selected, highlighting its content. Segmented controls are used to provide a selection between two or more options.

To create a segmented control in SwiftUI, we use the Picker view with the PickerStyle modifier set to SegmentedPickerStyle(). Here’s an example of a segmented control with three options:

struct ContentView: View {
  @State private var selection = 0

  var body: some View {
    Picker(selection: $selection, label: Text("Picker")) {
      Text("Option 1").tag(0)
      Text("Option 2").tag(1)
      Text("Option 3").tag(2)
    }
    .pickerStyle(SegmentedPickerStyle())
  }
}

Your preview should look like this:

Use the SegmentedPickerStyle to create a segmented control in SwiftUI.
Use the SegmentedPickerStyle to create a segmented control in SwiftUI.

In this example, you create a Picker with three Text views as options. Each option has a tag that identifies it. The selection property is bound to a state variable that keeps track of the user’s selection.

The pickerStyle modifier is set to .segmented to style the picker as a segmented control.

When the user selects an option, the selection variable is updated with the corresponding tag value.

That’s it! You now know how to create a segmented control in SwiftUI. It’s that easy.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.