How it works
Use a Picker to let people choose a single value from a set of mutually exclusive options. You bind the picker to a piece of state that holds the current choice, and supply the candidate values as its content; SwiftUI keeps the binding in sync as the selection changes. Reach for Picker whenever the answer is "exactly one of these," rather than free-form text or an on/off toggle. Its appearance adapts to the surrounding context, so the same declaration can render as a wheel, a menu, a segmented control, or an inline list depending on platform and style.
Bind the selection with a Binding
The
selectionparameter takes aBindingto the property that stores the chosen value, written with the$prefix. Hereselection: $flavorties the picker to the@Statevariableflavor, so picking an option writes the new value back and any view readingflavorupdates automatically.Label the picker
The first initializer argument provides the picker's label, describing what the choice represents. The string
"Flavor"labels this picker; depending on the container and style, it appears as a leading title (as it does insideForm) or is used for accessibility.Supply options in the content closure
The trailing closure lists the selectable views, one per option.
ForEach(flavors, id: \.self)generates aTextrow for each entry inflavors, turning the array into the picker's choices without writing each one by hand.Identify each option with tag(_:)
Each option must carry a
tagwhose type matches theselectionbinding, so SwiftUI can map a row to a value. Calling.tag(name)on everyText(name)makes each row's identity aString, matching theStringselection so the right row shows as selected and the right value is stored.Choose a presentation with pickerStyle(_:)
The
pickerStyle(_:)modifier controls how the options are presented without changing the binding or content..pickerStyle(.inline)lays the choices out directly within theForm; swapping in styles like.menu,.segmented, or.wheelchanges only the appearance.
.pickerStyle(.inline) to .pickerStyle(.segmented) to see the same Picker and $flavor binding render as a horizontal segmented control instead of an inline list.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 PickerDemo: View {
@State private var flavor = "Vanilla"
private let flavors = ["Vanilla", "Chocolate", "Strawberry"]
var body: some View {
Form {
Picker("Flavor", selection: $flavor) {
ForEach(flavors, id: \.self) { name in
Text(name).tag(name)
}
}
.pickerStyle(.inline)
Text("Selected: \(flavor)")
}
.padding()
}
}