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:

- (NSArray *)pickerData {
    
    if (!_pickerData) {
        _pickerData = @[@"Tom", @"Dick", @"Harry", @"Steve", @"Jones", @"Fred", @"Ninja", @"Mom"];
    }
    return _pickerData;
}

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

This content is for members only.

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:

[self.yourPicker selectRow:14 inComponent:0 animated:NO];




2 thoughts on “How to create a custom UIPickerView

Leave a Reply