Updated for Xcode 14.2
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, the picker will be collapsed down to a single list row that presents all the available options as a popup menu.
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 {
NavigationStack {
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 display all possible options – Mild, Medium, and Mature.
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 {
NavigationStack {
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 Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.