Updated for Xcode 13.3
Updated in iOS 15
SwiftUI’s picker views take on special behavior when inside forms, automatically adapting based on the platform you’re using them with. On iOS this behavior is particularly impressive, because the picker can be collapsed down to a single list row that navigates into a new list of possible options – it’s a really natural way of working with many options.
For example, this creates a form with a picker using an array for its items:
struct ContentView: View {
@State private var selectedStrength = "Mild"
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
Form {
Section {
Picker("Strength", selection: $selectedStrength) {
ForEach(strengths, id: \.self) {
Text($0)
}
}
}
}
}
}
}
Download this as an Xcode project
On iOS, that will appear as a single list row that you can tap to bring in a new screen showing all possible options – Mild, Medium, and Mature. Your current selection will have a checkmark next to it, and when you select a new option it will return to the previous screen with that now showing.
Tip: Because pickers in forms have this navigation behavior, it’s important you present them in a NavigationView
on iOS otherwise you’ll find that tapping them doesn’t work. This might be one you create directly around the form, or you could present the form from another view that itself was wrapped in a NavigationView
.
If you want to disable this behavior, you can force the picker to adopt its regular style by using the .pickerStyle(.wheel)
modifier, like this:
struct ContentView: View {
@State private var selectedStrength = "Mild"
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
Form {
Section {
Picker("Strength", selection: $selectedStrength) {
ForEach(strengths, id: \.self) {
Text($0)
}
}
.pickerStyle(.wheel)
}
}
.navigationTitle("Select your cheese")
}
}
}
Important: If you’re using Xcode 12, you need to use WheelPickerStyle()
rather than .wheel
.
SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.