2009-04-09 83 views
2

我有一个自定义的UITableViewCell实现(利用标签作为子视图),它正在呈现项目列表,但当我向下滚动并选择一个项目(比如说数字43)时,我看到一个单元格渲染在我选择的单元格的顶部出现在列表中的较早(从表中的第一个呈现页面上的第3个)。UITableViewCell在选择上覆盖?

这里是我的方法:

- (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; 
} 

回答

5

一般来说,这些类型的错误(看到从另一个行数据)的指示,你没有设置你的可重复使用的细胞的部分,所以它只是使用旧的数据,但我找不到任何未被重置的部分。

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

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

+0

是的,我认为您对Cell保留旧数据是正确的......我只是觉得很奇怪,这是触发在细胞选择上。你知道什么方法触发时选择被调用,将触发重新渲染?我不认为tableView:didSelectRowAtIndexPath:正在做它。 – Greg 2009-04-09 19:22:09