Updated for Xcode 12.5
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 {
Form {
Section {
Picker("Strength", selection: $selectedStrength) {
ForEach(strengths, id: \.self) {
Text($0)
}
}
}
}
}
}
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 adopts its regular style by using the .pickerStyle(WheelPickerStyle())
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(WheelPickerStyle())
}
}
.navigationTitle("Select your cheese")
}
}
}
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.