NEW: Learn SwiftUI with my free YouTube video series! >>

Pickers in forms

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

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.

If you want to disable this behavior, you can force the picker to adopts its regular style by using the .pickerStyle(.wheel) modifier, like this:

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

    }
}
    .pickerStyle(.wheel)

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5