0
0
Ios-swiftHow-ToBeginner ยท 4 min read

How to Use Picker in SwiftUI: Simple Guide with Examples

In SwiftUI, use the Picker view to let users select from multiple options. Bind the picker to a state variable and provide a list of choices inside the picker. Customize the style with modifiers like .pickerStyle().
๐Ÿ“

Syntax

The Picker requires a label, a binding to a state variable, and a list of selectable options inside a closure. Each option is typically a Text view tagged with a value.

  • label: Describes the picker purpose.
  • selection: A binding to a variable that stores the selected value.
  • content: The options users can pick from.
swift
Picker("Select a fruit", selection: $selectedFruit) {
  Text("Apple").tag("Apple")
  Text("Banana").tag("Banana")
  Text("Cherry").tag("Cherry")
}
Output
A picker UI showing options: Apple, Banana, Cherry with the label 'Select a fruit'.
๐Ÿ’ป

Example

This example shows a picker that lets the user choose a fruit. The selected fruit is shown below the picker.

swift
import SwiftUI

struct ContentView: View {
  @State private var selectedFruit = "Apple"

  var body: some View {
    VStack {
      Picker("Select a fruit", selection: $selectedFruit) {
        Text("Apple").tag("Apple")
        Text("Banana").tag("Banana")
        Text("Cherry").tag("Cherry")
      }
      .pickerStyle(SegmentedPickerStyle())
      Text("You selected: \(selectedFruit)")
        .padding()
    }
    .padding()
  }
}
Output
A segmented control with options Apple, Banana, Cherry and a text below showing the chosen fruit.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Not binding the picker to a @State variable, so selection doesn't update.
  • Forgetting to tag each option, which causes selection to fail.
  • Using incompatible types for tags and the bound variable.
  • Not setting a picker style, which may lead to unexpected UI on different devices.
swift
/* Wrong: Missing tags and no binding */
Picker("Pick", selection: $selected) {
  Text("One")
  Text("Two")
}

/* Right: Tags and binding match */
Picker("Pick", selection: $selected) {
  Text("One").tag(1)
  Text("Two").tag(2)
}
๐Ÿ“Š

Quick Reference

  • Picker(label:selection:content:): Main initializer.
  • .pickerStyle(): Customize appearance (e.g., WheelPickerStyle, SegmentedPickerStyle).
  • Binding: Use @State or @Binding for selection.
  • Tags: Each option must have a tag matching the selection type.
โœ…

Key Takeaways

Use Picker with a binding to a state variable to track selection.
Each option inside the picker must have a tag matching the selection type.
Customize the picker appearance with .pickerStyle() modifiers.
Always bind the picker to a compatible variable type to avoid runtime errors.
Test picker UI on different devices as styles may render differently.