Segmented Control in SwiftUI

DevTechie
DevTechie
Published in
4 min readFeb 11, 2022

--

Photo by Timo Volz on Unsplash

Segmented control from UIKit is rolled into Picker view in SwiftUI. With the help of pickerStyle modifier, we can get our good old segmented control back.

Picker is created by providing a selection binding, label, and content for the picker to display and pickerStyle of type .segmented turns default picker into a segmented control.

Let’s create an example to understand this a little better.

We will start with a State variable which will hold the current selection for the picker. We will use tag function to identify different values of picker view’s items. This tag value can be any hashable type and upon selection will modify our State variable which eventually will trigger UI update for the view. Next we will use pickerStyle to change our picker into a segmented control.

struct PickerExample: View {
@State private var selected = 0
var body: some View {
Picker("Choose course", selection: $selected) {
Text("SwiftUI")
.tag(0)
Text("UIKit")
.tag(1)
}
.pickerStyle(.segmented)
}
}

Using Strings for Selection

In previous example, we saw use of selection State variable to track currently selected value in segmented control. In that case selection variable stored…

--

--