Picker View Tutorial in iOS8 with Swift

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 Built for iOS8 and Xcode 6.

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

Go to the Storyboard, drag a Picker View from the Object Library to the top of the View Controller inside the Storyboard. Select the Picker View and select the Pin button on the bottom-right corner in the storyboard. Select the left,right and top pins and click the "Add 3 Constraints" button.

The Storyboard should look like this.

The Picker View must conform to the UIPickerViewDataSource and UIPickerViewDelegate protocol. Ctrl-click the Picker View and drag from the dataSource Outlet to the View Controller in the Document Outline. Repeat this step for the delegate Outlet.

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

var 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 numberOfComponentsInPickerView(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 out array to the corresponding row.

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

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

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