In SwiftUI, the Picker
is a popular form control that allows users to choose an option from a list of possibilities. In this blog post, we will explore how to use the Picker
view effectively.
To start, we need an array that contains the options we want to display. Let’s assume we have an array called cities
that contains the names of various cities:
var cities = ["Rome", "Milan", "Venice", "Florence"]
Next, we need a property to store the selected choice. We use the @State
property wrapper to track changes made by the user:
@State private var selected = "Rome"
Now, we can use the Picker
view to create our selection interface. The Picker
view requires two parameters: a label and the property used for the selected item. Within the closure, we use a ForEach
view to generate a Text
view for each option in the cities
array:
Picker("What's your favorite city?", selection: $selected) {
ForEach(cities, id: \.self) {
Text($0)
}
}
To see the complete code, here’s an example of how our ContentView
struct looks:
struct ContentView: View {
var cities = ["Rome", "Milan", "Venice", "Florence"]
@State private var selected = "Rome"
var body: some View {
Form {
Picker("What's your favorite city?", selection: $selected) {
ForEach(cities, id: \.self) {
Text($0)
}
}
}
}
}
When you run the code, you’ll notice that the default option is correctly displayed:
However, even in preview mode or the Simulator, you won’t be able to interact with the Picker
. To fix this, you need to wrap the Picker
in a NavigationView
:
struct ContentView: View {
var cities = ["Rome", "Milan", "Venice", "Florence"]
@State private var selected = "Rome"
var body: some View {
NavigationView {
Form {
Picker("What's your favorite city?", selection: $selected) {
ForEach(cities, id: \.self) {
Text($0)
}
}
}
}
}
}
Now, when you run the code, you’ll see that the label turns from gray to black:
You can tap on the label, and a list of options will appear, accompanied by a navigation link to go back:
By tapping on an option, you’ll see that the selected option is visually displayed instead of the default one:
Alternatively, instead of using an array for the options, you can directly use Text
views. In this case, make sure to add the tag()
modifier to each view, allowing you to identify each option:
struct ContentView: View {
@State private var selected = "Rome"
var body: some View {
NavigationView {
Form {
Picker("What's your favorite city?", selection: $selected) {
Text("Rome").tag("Rome")
Text("Milan").tag("Milan")
Text("Venice").tag("Venice")
Text("Florence").tag("Florence")
}
}
}
}
}
By following these steps, you can effectively use the Picker
view in your SwiftUI forms, allowing users to choose options effortlessly.