2009-04-09 82 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