0

我有一个包含电影和演员数组的模型对象。我正在尝试在同一个 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
4

3 回答 3

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;

}

并为您想要支持的每个数据源方法执行类似的操作。你应该没事!

于 2013-11-03T12:49:46.327 回答
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;
    }
}
于 2013-11-03T12:48:55.803 回答
0

你可以给每个选择器一个tag如下:

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

并且delegate methodsUIPickerView

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if(pickerView.tag)
    return self.firstArray.count;
    else
    return self.secondArray.count;
  }

等等

于 2013-11-03T12:50:47.123 回答