开发者

How to handle UIPickerView with two data sources?

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 c开发者_如何学运维licked, picker will display place's name.

Thanks


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];
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜