2013-08-01 49 views
1

我有這個來了幾次,每次我從來沒有找到一個「優雅」的解決方案。自定義更改的UITableViewCell文本顏色

問題: 我有一個客戶UITableViewCellXIBInventoryCustomCell。該單元格有UILabelsUILabel的默認文字顏色爲黑色。我有一行索引數組,其中UILabel文本顏色需要灰色。我在我的InventoryCustomCell中有一個公開的方法,它允許我設置UILabel的顏色。

公共方法是這樣的:

- (void)setCellAdded:(BOOL)cellAdded { 

    UIColor *cellTextColor; 
    if (cellAdded) { 
     self.thumbImageView.alpha = 0.5f; 
     cellTextColor = [UIColor lightGrayColor]; 
    } else { 
     self.thumbImageView.alpha = 1.0f; 
     cellTextColor = [UIColor blackColor]; 
    } 

    self.titleLabel.textColor = cellTextColor; 
    self.partNumberLabel.textColor = cellTextColor; 
    self.priceLabel.textColor = cellTextColor; 
    self.quanityLabel.textColor = cellTextColor; 
    self.addButton.titleLabel.textColor = cellTextColor; 
} 

在我UITableViewController類,我註冊與XIB類。

[self.inventoryListTable registerNib:[UINib nibWithNibName:@"InventoryCustomCell" bundle:nil] forCellReuseIdentifier:@"InventoryCustomCellID"]; 

在我cellForRowAtIndexPath我設置這樣的:

InventoryCustomCell *cell = (InventoryCustomCell *)[tableView dequeueReusableCellWithIdentifier:inventoryCellID forIndexPath:indexPath]; 

..... 
Product *product = .. is grabbed from NSFetchedResultsController 

if ([addedProducts containsObject:product.objectID]) 
    [cell setCellAdded:YES]; 
else 
    [cell setCellAdded:NO]; 

return cell; 

現在,如果我在setCellAdded添加斷點if塊是爲了將小區設置標籤顏色爲灰色輸入正確。所以我知道這實際上被稱爲。

我覺得這裏的問題是什麼,是表視圖試圖重用細胞,因爲它們都具有相同的標識符,它不現在哪些應該是灰色的,哪些不應該。但如果是這種情況,那麼我希望看到一些細胞隨機灰色,有些不在setCellAdded之後被稱爲第一次。事實並非如此。細胞沒有一個變成灰色,但是把它們變成灰色的呼叫始終是灰色的。

如果我使用的是默認的UITableViewCell s,我可能只是爲黑色/灰色的單獨的cellIdentifier。由於我使用的自定義UITableViewCell有一個筆尖,我必須註冊一個cellIdentifier我不能使用這種方法,而只保留一個XIB文件。

我還以爲會工作的唯一的事情是,如果我創建了一個新的廈門國際銀行有相同小區的看法,但添加的所有標籤是灰色的。然後我可以使用兩個cellIdentifier的方法,但這只是看起來很詭異。

+0

這些單元格在黑色文本表中顯示嗎? – Justin

+0

是的,他們確實顯示爲黑色 – random

+0

如果您不執行registerNib方法會發生什麼?如果你使用'會發生什麼[一個NSBundle mainBundle] loadNibNamed:@「InventoryCustomCell]' – Justin

回答

0

只需添加屬性在您的自定義單元格類的.h文件的UILabels。然後在tableView:cellForRowAtIndexPath:做這樣的事情:

InventoryCustomCell *cell = (InventoryCustomCell *)[tableView dequeueReusableCellWithIdentifier:inventoryCellID forIndexPath:indexPath]; 
cell.yourTextLabel.textColor = [UIColor grayColor]; 

return cell; 
+0

這不起作用,比你的幫助 – random

+0

我注意到你在註冊你的筆尖時使用了字符串,而在dequeueReusableCellWithIdentifier中使用了字符串變量。你確定這些字符串值是相同的嗎? – hgwhittle

+0

它們在兩個地方都是一樣的 – random

相關問題