SwiftUI Picker Tutorial

A picker includes one or more scrollable lists of values, each of which has a single selected value. In this tutorial a picker is displayed containing colors. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIPickerTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView : View {
    // 1.
    @State private var selection = 0
    let colors = ["Red","Yellow","Green","Blue"]
    var body: some View {
        // 2.
        Picker(selection: $selection, label:
        Text("Picker Name")) {
            ForEach(0 ..< colors.count) { index in
  1. A state property containing the selected index number of the values inside the picker.

  2. A picker is created containing the items of the colors array.

In the preview pane go to live view, the values can be selected by turning the wheel of the picker view.

The source code of the SwiftUIPickerTutorial can be downloaded at the ioscreator repository on Github.