68 - Create a Picker in SwiftUI

A picker is a user interface control that allows your user to pick one choice from a list of options. In SwiftUI, you can easily create a picker using the Picker view.

Here’s an example of how to create a picker and customize its appearance:

struct ContentView: View {
  let options = ["Frida Kahlo", "Georgia O'Keeffe", "Mary Cassatt", "Lee Krasner", "Helen Frankenthaler"]
  @State private var selectedOption = 0

  var body: some View {
    VStack {
      HStack {
        Image(systemName: "paintpalette")
          .foregroundColor(.blue)
          .padding(.trailing, 4)

        Text("Favorite artist:")
          .font(.title)

        Text(options[selectedOption])
          .font(.title)
          .padding(.leading, 4)
      }
      .padding()

      Picker("Options", selection: $selectedOption) {
        ForEach(options.indices, id: \.self) { index in
          Text(options[index])
            .font(.headline)
        }
      }
      .pickerStyle(.wheel)
      .padding()
    }
  }
}

Your preview should look like this:

Use the wheel modifier with Picker to create a picker wheel.

Here’s what this code does:

Creating a picker in SwiftUI is easy and customizable. By using the Picker view and applying different pickerStyle modifiers, you can create a wide range of picker interfaces for your users to interact with.