In this tutorial, we’ll be customising the UIPickerView properties in our iOS Application. In the previous tutorial, we implemented the UIPickerView class and discussed some of the important helper properties and functions.

UIPickerView

We know that UIPickerView requires the two protocols: UIPickerViewDataSource, UIPickerViewDelegate.

Besides the required methods that we had discussed, we can use the following methods to customize the UI of the UIPickerView.

Using the above three methods we can override the width and height of the cell, and the view of each cell.

Inside the viewForRow method, we can customize the UILabel by creating our own or just create any random custom view such as a UIImage + UILabel.

To change the background color of the UIPickerView simply use the backgroundColor property over the instance.

In the following section, we’ll first create a UIPickerView with a custom label. Later we’ll add a custom view in place of the custom label.

Project Storyboard

ios-custom-uipickerview-storyboard

We’ve added two UITextField and connected them in the ViewController.swift file.

Code

The code for the ViewController.swift file is given below:

In the viewForRow method, we have set the UILabel color and a system font.
We must update the text here.

UIToolbar Tint color is set on the Buttons present in the Toolbar.

The output when the above application was run on a simulator is:

ios custom uipickerview output

In the next section, we’ll create a Dynamic UIPickerView on the second UITextField. We will show a UIImage from the assets in the custom rows.

UIPickerView Row with UIImage

The code for the updated ViewController.swift file is given below;

In the above code, we’ve also added TextFieldDelegate Procol in order to detect which UITextField is focused. Based on that we display the relevant UIPickerView with the respective data.

In the textFieldDidBeginEditing method, we set the activeField Property to 1 or 2 based on the UITextField that is focused.

After that we update the UIPickerView by calling reloadAllComponents()

The output of the above application in action is given below

ios custom uipickerview output 2

This brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: