SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

Pickers


The Apple documentation defines the Picker as: ‘A control for selecting from a set of mutually exclusive values.’

In this post, we’ll explore the main types of pickers in SwiftUI:

  • Default Picker
  • Date Picker
  • Color Picker
  • Segmented Controller (yes, it’s a picker)
  • Wheel

Default Picker

struct ContentView: View {
    var films = ["A New Hope", "The Empire Strikes Back", "Return of the Jedi "]
    @State private var selectedFilm = "The Empire Strikes Back"

    var body: some View {
        VStack {
            Picker("Please choose a film", selection: $selectedFilm) {
                ForEach(films, id: \.self) { film in
                    Text(film)
                }
            }
            Text("You selected: \(selectedFilm)")
        }
    }
}


In this case, we want to select a film from a list of three film names. The Picker is displayed with the second film selected by default. The selectedFilm variable stores the name of the film chosen by the user.

Date Picker


It’s a Picker used to select a date. In this case, we have several options:

struct ContentView: View {
    @State private var date = Date()

    var body: some View {
        VStack {
                DatePicker(
                    "Start Date",
                    selection: $date,
                    displayedComponents: [.date, .hourAndMinute]
                )
            Text(date.ISO8601Format())
        }
    }
}


In this example, we set the DatePicker to the current date and time, displaying the date, hours, and minutes. Alternatively, we can choose to display only the date, only the time, or both. The date variable stores the selected date and time.


To display a calendar, we need to set the datePickerStyle to .graphical like this:

DatePicker("Start Date", selection: $date, displayedComponents: [.date, .hourAndMinute]).datePickerStyle(.graphical)

Color Picker


Sometimes, we want the user to choose a color, such as for settings or a drawing application. In this case, we use the ColorPicker. In the code below, the selected color is applied as the background color of the view:

struct ContentView: View {
    @State private var bgColor =
            Color(.sRGB, red: 1, green: 1, blue: 1)

    var body: some View {
        ZStack {
            Color(bgColor)
            ColorPicker("Choose the color", selection: $bgColor)
        }.ignoresSafeArea(edges: .all)
    }
}

Wheel

To display a wheel, simply change the pickerStyle to .wheel in the example above.

I encourage you to use these types of components whenever possible to minimize the need for users to type. Typing can be tedious and increases the risk of entering incorrect data.

Segmented Control


There is a dedicated post about this topic. Segmented Control in SwiftUI