[英]iOS UITableView: changing background color of table overrides background color of cells
我有一個問題,其中設置tableView的背景色會覆蓋我為單個單元格設置的背景色。 更具體地說,我有一個包含3行的表:頂部的單元格是深灰色,而底部的2個單元格是紅色:
http://imgur.com/otYlFMx,LvoLDzY,tXiJenw#0
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *sectionBackgroundColor = [UIColor colorWithRed:0.09f green:0.09f blue:0.09f alpha:1.0];
UIColor *menuItemBackgroundColor = [UIColor redColor];
if (indexPath.row == 0) {
cell.backgroundColor = sectionBackgroundColor;
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.text = @"MENU";
cell.textLabel.font= [UIFont systemFontOfSize:16.0];
cell.selectionStyle = false;
} else if (indexPath.row == 1) {
cell.backgroundColor = menuItemBackgroundColor;
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.text = @"Schedule";
cell.textLabel.font= [UIFont systemFontOfSize:18.0];
cell.imageView.image = [UIImage imageNamed:@"Schedule.png"];
} else if (indexPath.row == 2) {
cell.backgroundColor = menuItemBackgroundColor;
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.text = @"Contacts";
cell.textLabel.font= [UIFont systemFontOfSize:18.0];
cell.imageView.image = [UIImage imageNamed:@"Contacts.png"];
} else {
cell.backgroundColor = [UIColor blackColor];
cell.selectionStyle = false;
}
}
我正在嘗試做的是將所有那些空的,未使用的白色單元格置於底部黑色。 根據我的研究,設置tableView背景色可以做到這一點:
http://imgur.com/otYlFMx,LvoLDzY,tXiJenw#1
tableView.backgroundColor = [UIColor blackColor];
但是,正如您所注意到的,這一行代碼也將頂部兩個單元格的背景顏色也更改為黑色。 我進行了更多嘗試,並注意到一種通用模式,其中除最后一個單元格外,所有單元格背景色都將變為黑色:
(請參閱上面鏈接中的第三個圖像)
關於這里發生的事情有什么想法嗎? 幫助將不勝感激!
我已經嘗試過的某些方法不起作用(我會提供更多鏈接,但我的當前代表不允許我這樣做):
A)使單元格中的視圖不透明。 更改單元格中不同視圖的顏色。
cell.opaque = YES;
cell.backgroundView.opaque = YES;
cell.contentView.opaque = YES;
cell.backgroundColor = menuItemBackgroundColor;
cell.contentView.backgroundColor = menuItemBackgroundColor;
cell.backgroundView.backgroundColor = menuItemBackgroundColor;
B)設置tableView的backgroundView為nil。
tableView.backgroundView = nil;
C)設置tableView的backgroundView的背景色。
tableView.backgroundView.backgroundColor = [UIColor blackColor];
設置tableView的背景色會覆蓋我為單個單元格設置的背景色
沒錯 煩人,不是嗎? :)問題的實質在於,要么為單元格提供彩色的backgroundView
(比聽起來容易得多),要么等到tableView:willDisplayCell:forRowAtIndexPath:
然后在那里設置單元格的backgroundColor
。
通過以下變通辦法,您可以使用情節提要中指定的背景色,並避免在代碼中設置明確的顏色:
dequeueReusableCellWithIdentifier:
,雖然情節dequeueReusableCellWithIdentifier:
的背景色仍保持不變,但是將其保存,例如,保存在自定義UITableView
子類的屬性中。 willDisplayCell:
,使用在dequeueReusableCellWithIdentifier:
保存的值恢復backgroundColor
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.