Picker View iOS Tutorial

The picker is a slot-machine view to show one or more sets of values. Users select values by rotating the wheels so that the desired row of values aligns with a selection indicator. The user interface provided by a picker view consists of components and rows. A component is a wheel, which has a series of rows at indexed locations on the wheel. This tutorial is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use iOSPickerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Storyboard Setup

Go to the Storyboard. Add a Picker View to the main viewSelect the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag or right-click-drag from the Picker View to the ViewController class and create the following Outlet.

The Storyboard should look like this.

Coding

Go to the ViewController.swift file. The Picker View must conform to the UIPickerViewDataSource and UIPickerViewDelegate protocol. Change the class declaration line to

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

Change the viewDidLoad method to

override func viewDidLoad() {
    super.viewDidLoad()
        
    pickerView.delegate = self
    pickerView.dataSource = self
}

We must provide the Picker View with values. Add the following array in the ViewController class.

let colors = ["Red","Yellow","Green","Blue"]

The colors array will be the data source for our Picker View. The UIViewDataSource protocol requires delegate methods to define the number of components and rows of a picker. Implement these methods.

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
    
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return colors.count
}

We define one component with the number of rows equal to the number of array items. Next, we assign the data in our array to the corresponding row.

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return colors[row]
}

Project Execution

Build and Run the project, the different colors can be selected inside the Picker View.

You can download the source code of the iOSPickerTutorial at the ioscreator repository on Github.