UIPickerView 实现双向选择器

通常要求我们实现UIPickerView的双向选择器

那么首先Controller实现下面两个协议:UIPickerViewDelegate,UIPickerViewDataSource

//这个方法是用来设置UIPickerView几个选择器

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

//这个方法是用来设置每个选择器各自有多少行数据

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
    if (component == PickerOne) {
        return [array1 count];
    }
    return [array2 count];
}

//这个方法是向每个选择器中添加数据(动态加载的)
- (NSString *)pickerView:(UIPickerView *)pickerView
                      titleForRow:(NSInteger)row
                forComponent:(NSInteger)component{
    if (component == PickerOne) {
        return  [self.array1 objectAtIndex:row];
    }
    NSArray * array=[self.dictionary2 allValues];
    array=[array sortedArrayUsingSelector:@selector(compare:)];
    return [self.dictionary2 valueForKey:[array2 objectAtIndex:row]];
}

//这个方法是设置选择器各自的大小(宽度大小)
- (CGFloat)pickerView:(UIPickerView *)pickerView
    widthForComponent:(NSInteger)component{
    if (component==0) {
        return 120;
    }
    return 200;
}

//这个方法是当选择器选择的数据发生改变或是选择数据时响应的方法

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component{
    if (component==0) {
        NSLog(@"this is UMengFeedbackGender: %d" , row);
        self.UMengFeedbackGender=row;
    }
    if (component==1) {
        NSLog(@"this is UMengFeedbackAge : %d", row);
        self.UMengFeedbackAge=row;
    }
    NSLog(@"this is umeng.gender: %@, umeng.age :%@",
          [self.dictionary1 valueForKey:[NSString stringWithFormat:@"%d",
                                         self.UMengFeedbackGender]],
          [self.dictionary2 valueForKey:[NSString stringWithFormat:@"%d",
                                         self.UMengFeedbackAge]]);
    [self showButtonText:[self.dictionary1 valueForKey:[NSString stringWithFormat:@"%d",
                                                        self.UMengFeedbackGender]]
               stringAge:[self.dictionary2 valueForKey:[NSString stringWithFormat:@"%d",
                                                        self.UMengFeedbackAge]]];
}

实现相应的方法后要在视图编辑窗口给UIPickerView连接  代理  , 即右键连接UIPickerView  到 File's  Owner 上 ,弹出的 delegate 和 dataSource 都要选上。

你可能感兴趣的:(UIPickerView 实现双向选择器)