Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Picker in SwiftUI
Written by Team Kodeco

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.
Use the wheel modifier with Picker to create a picker wheel.

Here’s what this code does:

  • The ContentView struct is defined, which conforms to the View protocol.
  • An array options is created, containing the names of different artists.
  • The selected option is stored in a @State property called selectedOption, with an initial value of 0.
  • The body property of the view is defined, which represents the view’s content.
  • Inside the body, a VStack is created to vertically stack the views.
  • Inside the VStack, an HStack is created to display the “Favorite artist” section.
    • An Image view with the system name paintpalette is added, adding the SF Symbol paint palette icon.
    • The image is styled with a blue color and given some padding.
    • A Text view with the string “Favorite artist:” is added, representing the label.
    • Another Text view is added to display the selected artist’s name.
    • The text views are styled with a large font size and padding.
  • A Picker is added below the “Favorite artist” section to display the options.
    • The Picker displays a wheel-style interface for selecting options.
    • It uses a ForEach loop to iterate through the options array and create a Text view for each option.
  • The Picker and “Favorite artist” section are given some padding for spacing.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.