How to create a custom UIPickerView

Creating picker views is similar to creating table views: you supply an array of data for each component by conforming to the UIPickerViewDataSource protocol.

A component is equivalent to a section in a table view, and each component can have several sections. You can’t set much of this up in interface builder other than add the actual picker view to a position, and define the delegate and data source for your class (self in our example).

Setting up the picker

Let’s go through this step by step. We’re creating a single component picker and print its results. First we need an array of data – let’s create this as a custom initialiser for a property named pickerData:

Next we’ll conform to the data source protocol with these snazzy methods:

We specify the amount of data in each section (how many components, how many rows), and return an object to be displayed in each row – like we would specify the cell for a table view.

Return types for the UIView can be either a UILabel or a UIImage – which allows you to be rather creative. Alternatively, if you’re simply presenting NSString data, use this method instead:

You can specify how tall each picker row needs to be by adding this method and play with the value:

Likewise you can specify how wide a component should be by implementing pickerView:widthForComponent. This should display your UIPickerView.

Reacting to changes

Unlike the UIDatePickerView, the standard UIPicker does not have an IBAction you can hook up. Instead, we can confirm to the UIPickerViewDelegate protocol and implement didSelectRow:inComponent – much like we would implement didSelectRowAtIndexPath for a table view:

That’s all there’s to it!

Perhaps one more thing: when the picker shows the first item in the list will be pre-selected. If you’d like to pre-select a different item you can do so by calling this, perhaps in your viewDidLoad method:

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!