2010-04-09 34 views
12

我試圖設置我的UITableViewCells的標籤backgroundColor,它完全沒有任何作用。我想知道是否有另一種方式來做這件事,所以我問!UITableViewCell上的textLabel.backgroundColor不起作用

我嘗試這樣做:

cell.textLabel.backgroundColor = [UIColor redColor]; 
cell.backgroundColor = [UIColor redColor]; 

而且這是行不通的,別的嗎?

謝謝!

回答

41

我假設你在cellForRowAtIndexPath中試着這樣做。

按照UITableViewCell class reference

注意:如果你想(通過設置 通過由 的UIView宣佈 backgroundColor屬性單元格的背景顏色)來改變細胞的 背景顏色你必須在 tableView中執行:willDisplayCell:forRowAtIndexPath: 委託方法,而不是 tableView:cellForRowAtIndexPath: 的數據源。

所以做到這一點:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    cell.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell 
    cell.textLabel.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell 
    cell.textLabel.textColor = [UIColor yellowColor]; //can do here OR in cellForRowAtIndexPath 
} 

如果您需要在單元格顯示更精細的控制,一個簡單的方法是設計它IB和來自的cellForRowAtIndexPath筆尖加載它。請參見Table View Programming Guide中的this page上的「從筆尖文件加載自定義表格 - 查看單元格」部分。

+1

太棒了,爲此尋找無處不在。謝謝 – 2013-08-20 17:01:54

0

IOS 9.3的更新。這實際上在使用IOS 9.3的cellForRowAtIndexPath中正常工作。另請注意:要更改整個單元格的顏色,請使用:

cell.contentView.backgroundColor = [UIColor redColor];