2012-02-21 90 views
2

我有以下代碼,它爲UITableViewCell繪製分隔線和文本。它看起來很好,但當我滾動屏幕然後返回時,分隔線已消失,但文本仍然正常。有任何想法嗎?重複使用UITableViewCell問題

static NSString *aProgressIdentifier = @"CustomerCell"; 
       UITableViewCell *aCustomerCell = [iTableView dequeueReusableCellWithIdentifier:aProgressIdentifier]; 
       if (!aCustomerCell) { 
        aCustomerCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:aProgressIdentifier] autorelease]; 
        aCustomerCell.contentView.backgroundColor = [UIColor whiteColor]; 
        UIImageView *aLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 72, 800, 1)]; 
        aLine.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0]; 
        [aCustomerCell addSubview:aLine]; 
        [aLine release]; 
       } 

       CMACustomer *aCustomerObject = aCellObject; 
       aCustomerCell.textLabel.text = aCustomerObject.customerFullName; 
       aCustomerCell.detailTextLabel.text = nil;  
       aCell = aCustomerCell; 

回答

2

嘗試添加「aLine」圖像視圖作爲contentView的子視圖,而不是整個表本身。可能當單元格被重用,然後再次調用layoutSubviews時,contentView會重疊(白色背景)您的aLine。事實上,考慮到iOS默認單元格每次在屏幕上顯示時都會動態重繪和調整其子視圖。

所以我會嘗試這樣的:


[aCustomerCell.contentView addSubview:aLine]; 

如果這不起作用,你可以做什麼是完全刪除內容查看,並添加自己的自定義子視圖(做到這一點,如果(aCustomerCell內)!除非不在外面,你不會得到的細胞再利用的好處):


if (!aCustomerCell) { 
    aCustomerCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:aProgressIdentifier] autorelease]; 
    [cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; 
    UIImageView *aLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 72, 800, 1)]; 
    aLine.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0]; 
    [aCustomerCell.contentView addSubview:aLine]; 
    [aLine release]; 
} 

最後另一項檢查驗證室高度爲> 72(這似乎是一個微不足道的檢查,但其經常頭痛的源泉! )。

+0

雅的高度恰好是72,並且該線最初顯示,這意味着它的工作原理。我試過你發佈的第二個代碼,但它只給我所有沒有文本或任何東西的灰色單元格。 – Jon 2012-02-21 21:16:27

+0

我實際上已將行改爲71,現在所有作品。奇怪。 – Jon 2012-02-21 21:39:19

0

嘗試將其添加到內容查看

[aCustomerCell.contentView addSubview:aLine] 
+0

這沒有奏效,我用完整的方法更新了代碼,因爲問題在別處。 – Jon 2012-02-21 20:12:08

1

表視圖使用細胞池,所以你不能確保你得到任何給定的索引路徑是哪一個。您可以使用單元格或內容視圖,但一定要爲每個單元添加一條自定義行。

UIImageView *aLine = (UIImageView *)[cell viewWithTag:64]; 
if (!aLine) { 
    // etc. 
    UIImageView *aLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 72, 800, 1)]; 
    aLine.tag = 64; 
    [cell addSubview:aLine]; 
    // 
} 
// other formatting logic here, you can also hide/show aLine based on biz logic 
+0

我試過但沒有運氣。 – Jon 2012-02-21 20:09:45

+0

我用完整的方法更新了代碼,因爲問題在別處。 – Jon 2012-02-21 20:11:58

+0

喬恩 - 我的壞。看到我修改後的答案。 – danh 2012-02-21 20:13:20