top of page
Writer's pictureHui Wang

24. SwiftUI: Introducing Picker


Today I will show you how to use Picker.

Picker is similar to UIPickerView in UIKit and is mainly used to provide a scrolling list to facilitate user selection.


Knowledge points:

  • First, add the data source for the list.

  • Add another array property as the font color for each option in the Picker list.

  • Then add an integer property as the index value of the option in the selected state in the list, and add a @State property wrapper to it, so that this property is data-bound with the Picker in the UI.

private var fruits = ["Apple", "Grape", "Blueberry", "Banana"]
private var colors: [Color] = [.red, .green, .blue, .yellow]
@State private var selectedIndex = 0

  • Initialize a Picker and bind it to the selectedIndex property. When the user interacts with the Picker, the value of this property will change synchronously.

  • Set Picker's style to .wheel

Picker(selection: $selectedIndex) {
    ForEach(0 ..< fruits.count) {
        Text(fruits[$0])
            .foregroundColor(colors[$0])
    }
} label: {
    Text("Fruits")
}
.pickerStyle(.wheel)

  • Next, set the Picker content, and add a loop statement to iterate over the array.

  • Then display each element in the array through the Text view. At the same time, get the specified color from the color array as the font color of the Text view.

ForEach(0 ..< fruits.count) {
    Text(fruits[$0])
        .foregroundColor(colors[$0])
}

  • Add a Text view that displays what the user has selected.

  • Then add another Text view by extending the "+" method, showing what the user has selected.

  • As before, get the specified color from the color array as the font color of the Text view.

Text("You have chosen:")
+ Text("\(fruits[selectedIndex])")
    .foregroundColor(colors[selectedIndex])

Source Code:

struct ContentView: View {
    
    private var fruits = ["Apple", "Grape", "Blueberry", "Banana"]
    private var colors: [Color] = [.red, .green, .blue, .yellow]
    @State private var selectedIndex = 0
    
    var body: some View {
        VStack {
            Picker(selection: $selectedIndex) {
                ForEach(0 ..< fruits.count) {
                    Text(fruits[$0])
                        .foregroundColor(colors[$0])
                }
            } label: {
                Text("Fruits")
            }
            .pickerStyle(.wheel)
            Text("You have chosen:")
            + Text("\(fruits[selectedIndex])")
                .foregroundColor(colors[selectedIndex])
        }
    }
}

Visual effects:



Picker's other styles:

  • .pickerStyle(.menu)


  • .pickerStyle(.segmented)


 

Follow me on:

Comments


bottom of page