Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

ios - Can't set background color of UITableViewCell in IB

I have created a bunch of cells which I reuse in a table view. All of those cells just have different UILabels inside them and some UIImageViews (nothing covers the complete cell).

Setting the background color in IB has no effect (always white or transparent, can't say which one of them). But if I press Command-R (simulate interface) the cell has the correct background color in the simulator.

I tried to set it in tableView:cellForRowAtIndexPath: but it doesn't work like I would think either.

This does the trick:

cell.contentView.backgroundColor = [UIColor redColor];

but these have no effect (even if I set the cell.contentView.backgroundColor to clearColor):

cell.backgroundView.backgroundColor = [UIColor redColor];

cell.backgroundColor = [UIColor redColor];

I set all the layout/font/background stuff in IB. Any idea why this isn't working in this case?

Why do I need to modify the contentView's backgroundColor and not the backgroundView's?

It seems to be a common issue. Could somebody please point me in the right direction to (finally) understand how background colors are handled within a table view cell.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To change the background color of the cell, you have to do it in the willDisplayCell:forRowAtIndexPath: method. This is mentioned in the UITableViewCell documentation near the bottom of the Overview. So you need:

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

The contentView is just the recommended subview to put custom controls in so that the cell gets layed out properly when table editing is going on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...