Search code examples
ios5ios6uipickerview

UIPickerView Cascade-like Selection


Is it possible to dynamically filter the selection from one side with the other?

For example

| car types | color |

| Toyota | Blue, Yellow |

| Ford | Green, Orange, Purple |

| Ferrari | Red, Green, Yellow |

So when the UIPickerview is displayed, I can select the different types of cars. Upon selecting the type of car, I want to be able to only choose the specified colors.

At the moment I can just load all the car types and only one range of colors when the UIPickerView is displayed. I don't know if its possible to dynamically generate the right hand side with the option on the left.


Solution

  • It's actually quite simple to do. You need to return the relevant colours for component 1 depending on what is selected in component 0, e.g.:

    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
        //...
        case 1:
        {
            NSArray *colors = [self colorsWithSelection:self.selectedRow0];
            return colors[row];
        }
        //...
    }
    

    Then implement the following:

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        if (component == 0)
        {
            self.selectedRow0 = row;
            [pickerView reloadComponent:1];
            dispatch_async(dispatch_get_main_queue(), ^{
                [pickerView selectRow:0 inComponent:1 animated:YES];
            });
        }
    }
    

    Obviously this can be optimised, but it shows the idea.