改变cell.accessoryView和cell.editingAccessoryView的背景颜色

问题描述:

每当我向我的UITableViewCell添加一个accessoryView时,它不会传递背景颜色?我将UISwitch设置为我的accessoryView,并且我在cell.backgroundColor属性中设置的颜色只影响contentView而不影响accessoryView。 我已经尝试了所有设置为相同的值。我试图设置cell.backgroundView.backgroundColor和cell.accessoryView.backgroundColor属性为我想要的颜色,但没有任何工作。我也尝试在contentView中创建一个子视图,它解决了backgroundColor问题(通过避免它),但它创建了问题,当文本太长时,开关位于cell.textLabel的顶部。改变cell.accessoryView和cell.editingAccessoryView的背景颜色

有没有办法可以修改accessoryView的背景颜色,而无需在contentView中创建子视图,或者修改cell.textLabel的长度而无需创建UITableViewCell的子类?

在阅读文档(一种新颖的想法)后,我发现文章“A Closer Look at Table-View Cells”。它帮助我了解细胞的成分,我发现我的答案...

细胞是这样的......

alt text

由于cell.accessoryView是姐妹视图细胞。 contentView我不得不问cell.contentView它的超级视图,然后我能够一次改变两个视图的背景颜色。下面是什么代码看起来像......

// Cell Formatting 
cell.contentView.superview.backgroundColor = [UIColor greenColor]; 

我知道这是很简单,但我是一个新手,我花了长时间才放慢脚步,阅读文档。希望这有助于其他人在那里!

+7

我知道它有点晚了,但你需要设置单元格的颜色在'的tableView:willDisplayCell:forRowAtIndexPath:'方法:) – Illep 2012-01-26 16:42:41

+0

帮我,但作为一个额外的步骤,我不得不确保不在UITableViewCell的'superclass'上调用任何'setSelected'方法。看起来像这样将** accessoryView **的背景颜色设置为默认选择颜色。 – Aerows 2016-11-10 14:21:13

@Zak,首先感谢提醒我注意细胞布局的细节。很有帮助!
我只是想指出的是,下面的代码:

self.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]]; 

为我工作。结果是延伸到整个细胞的背景图像。 附件类型查看没有掩盖它!重要的部分是将此代码放入layoutSubviews您自定义单元类的方法,而不是放入cellForRowAtIndexPath在TableViewController类中找到。在我来说,我定义的类CustomCell和它里面我已经定义的标签,图像视图等

注意:下面的代码是不工作:

cell.contentView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]]; 

的tableView把时:(UITableView的*)tableView cellForRowAtIndexPat方法。它给我的背景覆盖单元格,但AccessoryTypeView是在它之上...

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    cell.backgroundColor = [UIColor yellowColor]; 
} 
+0

但我认为着色的东西应该属于视图类。 Adarsh VC的解决方案更好,因为它可以放在awakeFromNib中。 – johnlinvc 2012-08-16 03:36:59

UIView *myView = [[UIView alloc] initWithFrame:cell.frame]; 
myView.backgroundColor = [UIColor colorWithRed:214.00/255.00 green:233.00/255.00 blue:247.00/255.00 alpha:1.0]; 
cell.backgroundView = myView; 
[myView release]; 

如果你想与单元格的背景颜色相混合附属视图背景颜色,在iOS8上和斯威夫特这个工作就像在的tableView(_魅力,的cellForRowAtIndexPath :)方法:

let color = cell.contentView.backgroundColor 
cell.backgroundColor = color