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
.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.