2011-03-19 102 views
14

我想设置我的UITableViewCells的细胞背景,但我挣扎着UIAccessoryView的背景颜色。它不会改变。细胞背景和配件

任何人都可以帮助我使背景颜色的UIAccessoryView透明(或实际上任何其他颜色)?

这是我的代码

cell.textLabel.backgroundColor = [UIColor clearColor]; 
cell.accessoryView.backgroundColor = [UIColor clearColor]; 
cell.detailTextLabel.backgroundColor = [UIColor clearColor]; 
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

if(indexPath.row % 2) { 
    cell.contentView.backgroundColor = [UIColor clearColor]; 
} 
else { 
    cell.contentView.backgroundColor = [UIColor redColor]; 
} 

这里是说明问题

UIAccessoryView does not change background color.

回答

46

你需要设置的UITableViewCell的backgroundView性的图像。例如:

UIView* myBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease]; 
myBackgroundView.backgroundColor = [UIColor redColor]; 
myCell.backgroundView = myBackgroundView; 

如果你想要的东西更花哨,像一个红色渐变背景,你会实现的UIView的子类,在drawRect:绘制一个渐变,并用它作为backgroundView。

如果您想要自定义外观选定的表格单元格,您还可以设置selectedBackgroundView属性。

+0

太棒了!这是有效的,而且更容易!用渐变和'selectedBackgroundView'好主意非常感谢! – simonbs 2011-03-19 13:24:53

+0

非常感谢......在这里呆了很久,你的回答是第一个解决它的问题。 :) – 2013-06-15 01:08:04

+0

+1为好的答案,非常感谢。 – Shivaay 2014-02-24 06:38:15

4

在功能

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

使用下面的代码

cell.contentView.superview.backgroundColor = [UIColor redColor]; 

reference for more details

+1

效果很好,谢谢单行方法:-) – PetrV 2013-01-08 15:01:42

+1

谢谢你+1 – 2015-01-05 13:56:38

0

如果你想改变它的自定义类的UITableViewCell你可以使用:

override func layoutSubviews() { 
    super.layoutSubviews() 
    self.backgroundColor = UIColor.whiteColor() 
} 

更换背景awakeFromNib()init?(coder aDecoder: NSCoder)不起作用!