2

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 が (文字通りにも比喩的にも!) 保持されていることが期待されます。ただし、最初のいくつかの画面上のビューを最初から設定した後、(リサイクルされた、と思います) 非 nil の「reusingView」で呼び出されましたが、サブビューがないため、クラッシュしています既存のラベルを取得して変更しようとするとき。

私は何か誤解していますか?

4

1 に答える 1

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;
}
于 2013-05-16T14:49:53.597 に答える