cannot set background color of UITableViewCell in

2019-03-27 07:39发布

I started testing my app under simulator, because I don't have any iOS 6 device and stumbled upon weird problem. I cannot set backgroundColor property of UITableViewCell. If I st this:

cell.contentView.backgroundColor = [UIColor redColor];

it is working only for iOS 6, when I use this:

cell.backgroundColor = [UIColor redColor];

or this

[cell setBackgroundColor:[UIColor redColor]];

it is working only for iOS7.

When I use both cell.contentView and cell.backgroundColor it's working for both iOS... shouldn't it be one answer for such a 'easy' property? Or maybe it's some simulator bug?

UPDATE: If it changes anything in the same tableview and cells I cannot set accessoryType neither via StoryBoard nor code...

UPDATE2: for some reason setting tableview style to plain deleted all my changes, but grouped showed as expected...

5条回答
Evening l夕情丶
2楼-- · 2019-03-27 08:02

I don't see the problem in setting the background for the contentView AND directly to the cell. iOS 7 has change a lot this class. If you need to be compatible with old systems then you need to do this type of things.

So yes, you should use both:

cell.contentView.backgroundColor
cell.backgroundColor
查看更多
家丑人穷心不美
3楼-- · 2019-03-27 08:14

If you set (assuming you use standard cell):

cell.textLabel.backgroundColor = [UIColor clearColor];

...then you just have to use:

cell.contentView.backgroundColor = [UIColor redColor];

iOS 6 seems to copy table's background color to textLabel.

查看更多
▲ chillily
4楼-- · 2019-03-27 08:14

try to add this code:

cell.backgroundView.backgroundColor = [UIColor clearColor];
查看更多
手持菜刀,她持情操
5楼-- · 2019-03-27 08:15

In iOS6 you need to change the cell's backgroundColor in willDisplayCell. This works in iOS7 as well, precluding the need for version-specific code.

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor redColor]];
}
查看更多
地球回转人心会变
6楼-- · 2019-03-27 08:20

Try to change the cell's backgroundView color not the backgroundColor.

UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor whiteColor];
cell.backgroundView = myView;
查看更多
登录 后发表回答