Picker View iOS Tutorial

The picker view 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 8.3 and built for iOS 10.3

Project Setup

Open Xcode and create a new Single View Application.

Open Xcode and create a new Single View Application. For product name, use iOS10PickerViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Storyboard Setup

Go to the Storyboard. Add a PickerView to the main viewSelect the Picker View and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button to the top, left and right edge and select  "Add 3 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 iOS10PickerViewTutorial at the ioscreator repository on Github.