how to use a picker in swiftui

Asked on 08/05/2024

1 search

To use a picker in SwiftUI, you can follow these steps:

  1. Define the Picker: Use the Picker view to create a picker. You need to provide a selection binding and a label for the picker.

  2. Provide Options: Use a ForEach loop to provide the options for the picker.

  3. Handle Selection: Bind the picker to a state variable to handle the selection.

Here is a basic example:

import SwiftUI

struct ContentView: View {
    @State private var selectedOption = 0
    let options = ["Option 1", "Option 2", "Option 3"]

    var body: some View {
        VStack {
            Picker("Select an option", selection: $selectedOption) {
                ForEach(0..<options.count) { index in
                    Text(self.options[index]).tag(index)
                }
            }
            .pickerStyle(SegmentedPickerStyle()) // You can choose different styles
            .padding()

            Text("Selected option: \(options[selectedOption])")
        }
    }
}

Additional Context from WWDC Sessions

  • SwiftUI Essentials: This session covers various built-in capabilities of SwiftUI, including controls like Picker. You can explore more about SwiftUI's declarative and adaptive views in this session. SwiftUI essentials.

  • What’s new in StoreKit and In-App Purchase: This session introduces a new subscription picker API, which might be useful if you are dealing with subscription options in your app. What’s new in StoreKit and In-App Purchase.

  • Squeeze the most out of Apple Pencil: This session discusses the PKToolPicker, which is a specialized picker for tools in PencilKit. It provides insights into customizing tool pickers for drawing apps. Squeeze the most out of Apple Pencil.

For more detailed information, you can refer to the respective sessions and their documentation.