Multiple component UIPickerView in swift 4

 

 

Multiple component UIPickerView in swift - tutorial with sample code

 

Multiple component UIPickerView in swift

Multiple component UIpickerView in swift has two columns or two wheels that the user manipulate to select items. Basically, UIPickerView act as dropdown that is a list full of options. In this tutorial, we will learn how to create multiple component UIPickerView using swift language.

Steps to create multiple component UIPickerView

1: Create a new xcode project by selecting “Single View  App” template and name it “Multicomponent UIPickerView”.
 
Note: Please select development language as swift.
 
Select Singleview app template in xcode 9
 
 
2: Open “Main.storyboard” file.
 
Select Main.storyboard file
 
 
3: Drag UIPickerView and UILabel from object library. UILabel will be used to display selected value of uipickerview.
 
Drag and drop UIPickerView and UIlabel on to ViewController from object library
 
 
4: Add constraints to both UIPickerView and UILabel as shown below
 
Constraints given to UILabel

 

Constraints given to UIPickerView
 
 
5: Open “ViewController.swift” file. First declare IBOutlet’s for both controls, that were added in step number 3.
 

 
 
6: Open “Main.storyboard” and connect both the IBOutlet’s with their respective controls.
 
Connect IBOutlet with the UIPickerView and UILabel

 

 
7: In order to show options inside UIpickerView, we are going to take two arrays. With these arrays we will populate our UIPickerView.
 

 
 

 

UIPickerViewDataSource and UIPickerViewDelegate

8: As we are done with are arrays, its time to write down UIPickerViewDataSource and UIPickerViewDelegate methods.

 

 
9: If you run the code, you will see the following output.
If you run the code till now you will see output like this
 
On changing values, you will notice that label value will not be updated. So let us fix this problem.
 

UIPickerView row selection(get value selected by user)

10: To detect a picker selection, we need to implement another delegate method named as “didSelectRow”. Below is the code

 
11: Run the code and you will see whenever you change UIPickerView values, label will get updated and display value as per user selection.
 

Complete code: 

Where to go from here:

In this tutorial, we learned how to create and use multiple component UIPickerView or multi component picker in swift language.

Download source code for Multicomponent-UIPickerView.zip

%d bloggers like this: