SwiftUI: Working with Picker
2 min readSep 8, 2022
Picker is a control that allows you to select a value from a set of mutually exclusive values.
You create a picker by providing a selection binding, a label, and the content for the picker to display.
Set the selection
parameter to a bound property that provides the value to display as the current selection.
Example, we’re having a list of fruits
and a State
variable to hold the selected fruit:
Note: The default style for the picker is (automatic)
import SwiftUIstruct ContentView: View { let fruitList = ["Apple", "Mango", "Banana", "Grapes"]
@State var myFruit : String = "Apple"var body: some View {
VStack {
Picker("Select color", selection: $myFruit) {
ForEach(fruitList, id: \.self) {
Text($0)
}
}
.pickerStyle(.wheel)//Sets the style for pickers
}
}
}
You can customize the appearance and interaction of pickers using styles that conform to the PickerStyle
protocol, like segmented
or menu
. By just adding.pickerStyle(.segmented)
in your code.