2选择器不显示值

时间:2015-10-18 20:22:16

标签: objective-c uipickerview

我目前有2个选择器设置到我的viewController.h

@interface viewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UIPickerView *lPicker;
@property (weak, nonatomic) IBOutlet UIPickerView *rPicker;

@end

我的lPicker.tag = 0,而rPicker.tag = 1

在我的viewController.m实现文件中

我定义了以下方法......

NSArray *data1 = {@"one", @"two", @"three" };
NSArray *data2 = [NSArray arrayWithObjects: [UIImage imageNamed:@"img1.png"],[UIImage imageNamed:@"img2.png"], nil];

-(NSInteger) numberOfComponentsInPickerView:(UIPickerView*)pickerView {
    return 1; //both contain only 1 column
}

-(NSInteger) pickerView:*UIPickerView *) pickerView numberOfRowsInComponent:(NSInteger)component {
    if(pickerView.tag == 0) return data1.count; if(pickerView.tag == 1) return data2.count;
}

现在我遇到以下问题,在lPicker上我要显示data1中的值,而在右侧选择器上我想显示data2的值。

我尝试过创建方法 - (id)pickerView,但不能同时返回NSString *和UIImageView。

如果我实现类似......

之类的东西,那就行不通了
-(id) pickerView:(UIPickerView *) pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *) view {
    if(component == 0) {
        UILabel *label = [UILabel alloc];
        label.text = [data objectAtIndex:row];
        [view addSubview:label];
        return view;
    }
    if(component == 1) {
        UIImageView *image = [[UIImageView alloc] initWithImage: [data2 objectAtIndex:row]]; 
        [view addSubview: image];
        return view;
    }
    return view;
}

1 个答案:

答案 0 :(得分:1)

正如目前所写,您对重用视图做出了错误的假设。您还需要更改确定使用哪个选取器的方式。并修复方法的返回值。

试试这个:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    if (pickerView.tag == 0) {
        UILabel *label = (UILabel *)view;
        if (!label) {
            [[UILabel alloc] init];
        }
        label.text = data1[row];
        [label sizeToFit];

        return label;
    } else {
        UIImageView *image = (UIImageView *)view;
        if (!image) {
            image = [[UIImageView alloc] init];
        }
        image.image = data2[row];
        [image sizeToFit];

        return image;
    }
}