In this post we’ll learn:
- How to create a segment control.
- How to customize the look and feel of a segment control.
Create the segment control
Let’s start by creating a segment control that allows choosing from the days of the week:
struct SegUIView: View {
@State private var daySelected = 0
var body: some View {
VStack {
Picker("Choose a day", selection: $daySelected) {
Text("Mo").tag(0)
Text("Tu").tag(1)
Text("We").tag(2)
Text("Th").tag(3)
Text("Fr").tag(4)
Text("Sa").tag(5)
Text("Su").tag(6)
}
.pickerStyle(.segmented)
Text("Selected the day \(daySelected)")
Spacer()
}.padding()
}
}
So, the Segment Control is created by using a Picker and setting its style to segmented. If you remove this style, the default Picker appears as a contextual menu.
The state variable daySelected stores the tag value of the selected item. We then simply display this value in a Text.
Thus we have: