SwiftUI Segmented Control Tutorial

A segmented control is a set of two or more segments, each of which functions as a mutually exclusive button. In this tutorial a segmented control will be displayed and a text view will be updated with the contents of the selected segment . SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUISegmentedControlTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView : View {
    // 1.
    @State private var selectorIndex = 0
    @State private var numbers = ["One","Two","Three"]
  
    var body: some View {
        VStack {
            // 2
            Picker("Numbers", selection: $selectorIndex) {
                ForEach(0 ..< numbers.count) { index in
                    Text(self.numbers[index]).tag(index)
                }
            }
            .pickerStyle(SegmentedPickerStyle())
          
            // 3.
            Text("Selected value is: \(numbers[selectorIndex])").padding()
        }
    }
}
  1. each item in a selector has a tag value with index number starting at 0.

  2. A segmented control is displayed containing the items from the numbers array.

  3. The selected value in the segmented control is displayed

In the preview pane select the live preview button. Select a segmented control item and the text view will update.

The source code of the SwiftUISegmentedControlTutorial can be downloaded at the ioscreator repository on Github.