如何在同一个视图控制器中使用2个不同的选择器显示2个不同的数组?

时间:2013-11-03 12:28:22

标签: objective-c uipickerview uipickerviewdatasource

我有一个包含电影和演员数组的模型对象。我试图在同一个ViewController中填充2个选择器(1个选择器和电影,另一个选择演员)。请帮忙,因为我还在学习它的工作原理。

谢谢!

我的代码如下......

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    self.model = [[MovieModel alloc] init];


    for(int i = 0; i < self.model.count; i++){
        NSString *movies = [self.model movieForIndex:i];
        NSLog(@" Movie = %@", movies);
    }

    for(int i = 0; i < self.model.count; i++){
        NSString *actors = [self.model actorForIndex:i];
        NSLog(@" Actor = %@", actors);
    }


}

//这是我遇到问题的地方。谢谢!!!

#pragma mark - Picker View Delegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {


    if (component == 0){

        return [self.model movieForIndex: row];

    }

    else if (component == 1){

        return [self.model actorForIndex: row];

    }

    else
        return nil;

}



#pragma mark - Picker View Data Source

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {

    return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

    return self.model.count;

}

@end

3 个答案:

答案 0 :(得分:1)

您会注意到数据源方法中存在“pickerView”参数。此参数告诉您正在为两个选择器中的哪一个返回数据。

因此,假设您将两个选择器视图连接到两个不同的“IBOutlet”属性或ivars(实例变量),如下所示:

IBOutlet UIPickerView * moviePicker;
IBOutlet UIPickerView * actorPicker;

现在,在您的数据源方法中,您可以执行以下操作:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {


    if (pickerView == moviePicker){

        return [self.model movieForIndex: row];

    }

    else if (pickerView == actorPicker){

        return [self.model actorForIndex: row];

    }

    else
        return nil;

}

对要支持的每种数据源方法执行类似的操作。你应该没事!

答案 1 :(得分:0)

首先,您需要确保您的ViewController实现UIPickerViewDataSource和UIPickerViewDelegate。

您需要将选择器添加到视图中:

UIPickerView *moviesAndActorsPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[moviesAndActorsPicker setDelegate:self];
[self.view addSubview:moviesAndActorsPicker];

你的选择器有两个组件 - 1个用于电影,1个用于演员:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

然后设置每个组件的行数:

    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    // differentiate which component it is
    if (component == 0) { // movies
        return movies.count;
    }
    else { // component = actors
        return actors.count;
    }
}

答案 2 :(得分:0)

您可以为每个选择器提供tag,如下所示:

self.firstPicker.tag = 1;
self.secondPicker.tag = 2;

以及delegate的{​​{1}} methods

UIPickerView

等等