UITableViewCell在选择时被覆盖?

Gre*_*reg 2 iphone objective-c

我有一个自定义的UITableViewCell实现(利用标签作为子视图)正确地呈现项目列表,但是当我向下滚动并选择一个项目(比如说第43个中的100个)时,我看到了前面一个单元格的渲染列表(例如,表格中第一个渲染页面上的数字3)显示在我选择的单元格的顶部.

这是我的方法:

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    // index of table view correlates to index of array
    Card *card = [cards objectAtIndex:indexPath.row];

    UILabel *cardNameLbl = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 3.0, 200.0, 18.0)] autorelease];
    cardNameLbl.tag = CARD_NAME_TAG;    
    cardNameLbl.text = card.name;
    cardNameLbl.font = [UIFont systemFontOfSize:12.0];
    cardNameLbl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
    [cell.contentView addSubview:cardNameLbl];

    UILabel *cardNumLbl = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 21.0, 100.0, 18.0)] autorelease];    
    cardNumLbl.tag = CARD_NUM_TAG;
    cardNumLbl.text = card.number;
    cardNumLbl.font = [UIFont systemFontOfSize:12.0];
    cardNumLbl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; 
    [cell.contentView addSubview:cardNumLbl];

    UILabel *cardTypeLbl = [[[UILabel alloc] initWithFrame:CGRectMake(110.0, 21.0, 200.0, 18.0)] autorelease];  
    cardTypeLbl.tag = CARD_TYPE_TAG;
    cardTypeLbl.text = card.type;
    cardTypeLbl.font = [UIFont systemFontOfSize:12.0];
    cardTypeLbl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;    
    [cell.contentView addSubview:cardTypeLbl];

    UILabel *cardQuantityLbl = [[[UILabel alloc] initWithFrame:CGRectMake(250.0, 3.0, 50.0, 18.0)] autorelease];    
    cardQuantityLbl.tag = CARD_QUANTITY_TAG;
    cardQuantityLbl.text = [NSString stringWithFormat:@"%d", card.have];
    cardQuantityLbl.font = [UIFont systemFontOfSize:12.0];
    cardQuantityLbl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
    [cell.contentView addSubview:cardQuantityLbl];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Cra*_*tis 5

通常,这些类型的错误(从另一行中查看数据)表示您没有设置可重用单元的部分,因此它只是使用旧数据,但我找不到任何未重置的部分.

但是,你应该做的一件事,实际上可能解决了这个问题,是子类UITableViewCell,它将这些标签维护为ivars.然后,您可以初始化标签并将其作为子视图添加一次,在init方法中或您选择的任何其他位置.

目前正在发生的事情是:每次你抓住一个可重复使用的单元格时,它可能已经有了之前的那些标签,而你只是在子视图之上堆积了更多的子视图.(除非我弄错了,并且可重用的单元格在返回之前清除了它的子视图.)