UIPickerVIew中的重用视图viewForRow:丢失其子视图?

时间:2013-05-16 14:33:37

标签: ios uipickerview

我正在尝试在UIPickerView中重复使用包含子视图的视图:

- (UIView *)pickerView:(UIPickerView *)pickerView 
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component 
           reusingView:(UIView *)view
{
    UILabel* label = nil;
    if (view == nil) {
        view = [[UIView alloc] init];
        label = [[UILabel alloc] init];
        [view addSubview:label];
    }
    if (label == nil) {
        label = view.subviews[0]; // Exception here because there are no subviews
    }
    ...

如果我的“reusingView”UIView在输入时设置,我希望它保留(字面上和图形上!)我添加的子视图UILabel。然而,在从头开始设置前几个屏幕视图后,我被称为(回收,我假设)非零“reusingView”,但它没有任何子视图,所以我崩溃了当试图让现有的标签改变它时。

我误解了什么吗?

1 个答案:

答案 0 :(得分:2)

我无法复制您的问题。我使用以下代码创建了一个简单的项目,这与您的代码非常相似。我在标签上添加了一个框架,并为背景着色,以便我可以看到发生了什么。你能看到你所拥有的会产生结果差异的任何差异(也许问题出在你未展示的“......”区域)?

- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker.dataSource = self;
    self.picker.delegate = self;
}

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

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 10;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* label = nil;
    if (view == nil) {
        view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blueColor];
        label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 22)];
        label.text = @"test";
        [view addSubview:label];
    }
    if (label == nil) {
        NSLog(@"%@",view.subviews);
        label = view.subviews[0]; // I do get subviews here.
    }
    return view;
}