How it works
SegmentedPickerStyle is a picker style that lays out a Picker's options as a horizontal row of adjacent segments, with the current selection drawn as a highlighted segment. Reach for it when a picker has a small, fixed set of mutually exclusive choices that all benefit from being visible at once, rather than hidden behind a menu or wheel. Because it conforms to PickerStyle, you apply it through the pickerStyle(_:) modifier, leaving the picker's content and selection binding unchanged while only the presentation switches to a segmented control.
Build a Picker with a selection binding
SegmentedPickerStylestyles an existingPicker, so you first create one bound to state. HerePicker("Flavor", selection: $flavor)drives its choice from@State private var flavor, and the style changes how those choices are drawn without touching the binding.Tag each option so a segment maps to a value
Every selectable view inside the picker needs a
tagwhose type matches the selection. The threeTextrows carry.tag(0),.tag(1), and.tag(2); the segmented control renders one segment per tagged option and writes the matching value back toflavorwhen a segment is tapped.Apply the style with pickerStyle(SegmentedPickerStyle())
The
pickerStyle(_:)modifier takes anyPickerStylevalue and reshapes the picker accordingly. PassingSegmentedPickerStyle()turns the vertical list of options into a single horizontal segmented control, highlighting the segment whose tag equals the current selection.Use the no-argument initializer
SegmentedPickerStylehas a single parameterless initializer,SegmentedPickerStyle(), so there is nothing to configure on the style itself — sizing and emphasis follow the layout it is given. In modern SwiftUI you can write the same thing as the.segmentedshorthand on thePickerStyleprotocol.
Text("Mint").tag(3) inside the Picker and watch the segmented control split into four equal-width segments to accommodate it.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct SegmentedPickerStyleDemo: View {
@State private var flavor = 1
var body: some View {
Picker("Flavor", selection: $flavor) {
Text("Vanilla").tag(0)
Text("Chocolate").tag(1)
Text("Strawberry").tag(2)
}
.pickerStyle(SegmentedPickerStyle())
.padding()
}
}