NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Pickers in forms

Paul Hudson    @twostraws   

Updated for Xcode 12.0

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 {
    var strengths = ["Mild", "Medium", "Mature"]

    @State private var selectedStrength = 0

    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker(selection: $selectedStrength, label: Text("Strength")) {
                        ForEach(0 ..< strengths.count) {
                            Text(self.strengths[$0])

                        }
                    }
                }
            }.navigationBarTitle("Select your cheese")

        }
    }
}

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 wrap them in a NavigationView on iOS otherwise you’ll find that tapping them doesn’t work.

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:

Picker(selection: $selectedStrength, label: Text("Strength")) {
    ForEach(0 ..< strengths.count) {
        Text(self.strengths[$0])

    }
}
    .pickerStyle(WheelPickerStyle())
Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.1/5

Link copied to your pasteboard.