SwiftUI Picker

The Picker provided by SwiftUI allows for easy creation of picker views to select from multiple options. The options can be passed in different ways, including an array or an enum, and the picker can be stylized as well.

Basic Code Example

var colours = ["red", "blue", "yellow"]
@State private var selectedColour = 0
 
Picker(selection: $selectedColour, label: Text("Select Colour")) {
  ForEach(0..<colours.count) {
    Text(colours[$0])
  }
}

The example above is a Picker that takes its selector options from an array of ‘colours’, defined in line 1. The picker itself in line 4 takes in a selection binding ‘$selectedColour’, which provides the current value for display. In this case, the state variable selectedColour is initially set to 0 in line 2, so the picker will initially be selected onto ‘red’, the element at index 0. The label parameter takes in a view (ex. Text), which is typically used to describe the purpose of the picker, and doesn’t appear in the view.

The content of the picker in this case are Text views iterated using a ForEach line in line 5, which will display each element of the ‘colours’ array as an option in the picker.

Stylizing the Picker

var colours = ["red", "blue", "yellow"]
@State private var selectedColour = 0
 
Picker(selection: $selectedColour, label: Text("Select Colour")) {
  ForEach(0..<colours.count) {
    Text(colours[$0])
  }
}
.pickerStyle(SegmentedPickerStyle())

Using the code from the previous example, we can modify our picker with the .pickerStyle modifier, and pass in a different style to change our picker. The default style is a vertical wheel, and the example above uses SegmentedPickerStyle() which will show the options in a row.

Picker Using Enum

enum Animal: String, CaseIterable, Identifiable {
    case dog
    case cat
    case bird
    var id: String { self.rawValue }
}

@State private var selectedAnimal = Animal.dog

Picker("Animal", selection: $selectedAnimal) {
  ForEach(Animal.allCases) { animal in
    Text(animal.rawValue)
  }
}

Instead of passing an array, enum cases can be used. The enum of ‘Animal’ includes dog, cat, and bird, and so the Picker in this case takes in “Animal”, a LocalizedStringKey, and another selection binding ‘$selectedAnimal’, which is defined in line 8 to initially pick ‘dog’.

Similar to the first example, the content of the picker is defined using a ForEach to iterate through each animal, and to display the animal.rawValue (the string itself) as text.

Share
Tweet
Pin
Share
Buffer