tags:

views:

72

answers:

2

Hi, is it possible to handle two data sources in the UIPickerView?

I have here a segmented control that would control the display of the picker view. So, for example, when first segment is clicked, the picker will display person's name. Then, when second segment is clicked, picker will display place's name.

Thanks

A: 

You can check state of segmented control in your UIPickerView delegates (UIPickerViewDelegate and UIPickerViewDataSource) and return necessary values, depending on this state.

And, of course, you can create two objects (conforming to necessary protocols) and just reset delegates on segment state change. But I think this way is generally worse.

kpower
Thanks for all the responses.
devb0yax
A: 

Not directly -- the UIPickerView can only have one data source at a time. However, you can switch data source when the user changes the segment. Note that you need to change the delegate of the picker view too, since it is the delegate that supplies the actual content of the picker.

Here is an example where you have two objects that implement UIPickerViewDataSource and UIPickerViewDelegate. The method is invoked when the user clicks on either of the segments in the control:

- (void)segmentedControlValueChanged {
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
            pickerView.delegate = personDelegate;
            pickerView.dataSource = personDelegate;
            break;
        case 1:
            pickerView.delegate = placeDelegate;
            pickerView.dataSource = placeDelegate;
            break;
        default:
            break;
    }
    [pickerView reloadComponent:0];
}

But honestly, I think a better solution is to just have your pickerView:titleForRow:forComponent look at the segmented control. Assuming you have two NSArrays called persons and places:

- (NSString *)pickerView:(UIPickerView *)pickerView 
              titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *result;
    switch (segmentedControl.selectedSegmentIndex) {
        case 0:
            result = [self.persons objectAtIndex:row];
            break;
        case 1:
            result = [self.places objectAtIndex:row];
            break;
        default:
            result = @"Error!";
            break;
    }
    return result;
}


- (void)segmentedControlValueChanged {
    [pickerView reloadComponent:0];
}
Rolf Staflin