Picker in SwiftUI is a control that let users pick a value from a set of mutually exclusive values. It gives users a range of options to choose from. For example, you can use a picker to let users choose a country.
To track the selection of the picker, you must have to bind it to a state variable as we did with many other controls. This state variable also can help us to set a default value for the picker.
Now let’s see an example of creating a picker to choose a country from a list of countries:
var countries : Array = ["United States", "United Kingdom", "Germany", "India", "Singapore"]
@State private var selectedCountry = "Germany"
var body: some View {
Picker("Choose your country ", selection: $selectedCountry) {
ForEach(countries, id: \.self) {
Text($0)
}
}
Text("Selected country: \(selectedCountry)")
}
Below is how our picker will look on the device:
In our above code, we are using the ForEach
loop to list all the countries from the array in our picker as picker items or options. Using a Text view, the value of our selected picker is shown.
However, if you want, you can put the items one by one in the picker without using any ForEach loop or array. Here is what I mean given in this example:
Picker("Choose your country ", selection: $selectedCountry) {
Text("United States").tag(0)
Text("United Kingdom").tag(1)
Text("Germany").tag(2)
Text("India").tag(3)
Text("Singapore").tag(4)
}
It is possible to also set a picker style to give it different looks other than the default. The above style of the picker is the default. The default picker style depends on the device. in iOS 16, the default style accepts the menu as the picker style.
We haven’t set the style by ourselves. But if you want, you can choose a style. Applying style to a picker will not affect its functionality.
The pickerStyle()
modifier can be used to provide the design to our picker. Here is given an example where we have provided the .wheel
style:
var countries : Array = ["United States", "United Kingdom", "Germany", "India", "Singapore"]
@State private var selectedCountry = "Germany"
var body: some View {
Picker("Choose your country ", selection: $selectedCountry) {
ForEach(countries, id: \.self) {
Text($0)
}
}
.pickerStyle(.wheel)
Text("Selected country: \(selectedCountry)")
}
Now our picker will look like this:
Isn’t look cool? Well, there is more style available in SwiftUI for your picker.