How to load data to the Picker View in Swift

In this tutorial I am going to show you how to load data to the Picker View in IOS.

First you can place the Picker View control on the ViewController

To work with Picker View you need two protocols named UIPickerViewDataSource UIPickerViewDelegate.
Now you need to conform these protocols to ViewController class

You have two required methods in UIPickerViewDataSource protocol
func numberOfComponents(in: UIPickerView)
func pickerView(UIPickerView, numberOfRowsInComponent: Int)
These methods are used to specify
(a) How many components you have in your Data Scouce
(b) How many rows in your Data Source

For this example I will make a simple array to represent days of the week

Then I am returning the number of components in following function since I have one dimensional array I have to retun 1

Then, returning the number of rows in array

In addition to above methods you need one method to conform from the UIPickerViewDelegate protocol
func pickerView(UIPickerView, titleForRow: Int, forComponent: Int)
In this method I am going to return the element of the array based on the row

So now you can have a look at the completed code

 

Important

You need to connect dataSource and delegate to ViewController

You can open the Connection Inspector window and add the connection as shown in the below screen

In the same manner you can connect delegate and the ViewController

Now build and run the program and you can see the following screen in your simulator

Leave a Reply

Your email address will not be published. Required fields are marked *