如何在同一视图控制器上为不同的选取器视图设置不同的数据集

时间:2014-04-04 13:58:44

标签: ios objective-c uipickerview

我已经看过大量的教程,展示了如何使用多列选择器视图执行此操作,但对于我正在处理的应用程序,我有2个选择器视图,其中有两个完全不同的数组要填充来自2个不同阵列的数据?

2 个答案:

答案 0 :(得分:1)

所有UIPickerViewDelegate方法都有UIPickerView *参数。

答案 1 :(得分:1)

viewDidLoad或类似的地方:

UIPickerView *firstPickerView = [[UIPickerView alloc] init];
firstPickerView.dataSource = self;
firstPickerView.delegate = self;

UIPickerView *secondPickerView = [[UIPickerView alloc] init];
secondPickerView.dataSource = self;
secondPickerView.delegate = self;

NSArray *firstPickerSource = ...  // populate with some data
NSArray *secondPickerSource = ... // populate with some data

稍后,在您的dataSource和委托方法中:

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(pickerView == firstPickerView)
        return [firstPickerSource count];
    else
        return [secondPickerSource count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(pickerView == firstPickerView)
        return [firstPickerSource objectAtIndex:row];
    else
        return [secondPickerSource objectAtIndex:row];
}

另外,您可以在创建选择器视图时tag pickerView.tag == 1查看pickerView == firstPickerView或类似的内容,而不是{{1}}