mjbn mjbn - 11 months ago 67
iOS Question

Trying to create a UIPickerView with 3 columns and different row lenghts

I'm trying to create a UIPickerView with three columns and different row count for each column. The picker view comes up but only shows 3 items per column. What I'm doing wrong? Thanks.

_pickerData = @[ @[@"blanc", @"1/8", @"1/4", @"1/2", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10"],
@[@"blanc", @"1/8", @"1/4", @"1/2", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10"],
@[@"item 2", @"item 3", @"item 4", @"item 5", @"item 6", @"item 7", @"item 8", @"item 9", @"item 10"]];

// The number of columns of data
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
return 3;

// The number of rows of data
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
return _pickerData.count;

// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
return _pickerData[component][row];


Your picker is only showing 3 items per column because that's what's provided by the - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component method. Whatever number returned from this method is how many rows will appear in a given column (aka component). You are returing _pickerData.count here, and there are 3 items in your _pickerData array, so this makes sense. Note, the "count" of an array counts how many first level objects there are in the array - not how many objects are within each of those objects.

What I imagine you want to do is return _pickerData[component].count instead of _pickerData.count. This will grab a specific array within your picker data and return the number of items within that array, which seems like it's what you are looking for. You're already doing something similar in pickerView:TitleForRow:forComponent so I think you understand the concept already. Almost there.

To deal with your 'id' warning, you can cast the object to tell the compiler what kind of object it is dealing with:

NSArray *array = (NSArray*)_pickerData[component];
return array.count;