SwiftUI Forms: Picker - Choosing Options Made Easy
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:
1 | 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:
1 | 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:
1 | Picker("What's your favorite city?", selection: $selected) { |
To see the complete code, here’s an example of how our ContentView
struct looks:
1 | struct ContentView: View { |
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
:
1 | struct ContentView: View { |
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:
1 | struct ContentView: View { |
By following these steps, you can effectively use the Picker
view in your SwiftUI forms, allowing users to choose options effortlessly.
tags: [“SwiftUI”, “forms”, “Picker”, “iOS development”]