无法在IB中设置UITableViewCell的背景色
收藏

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).

在IB中设置背景颜色无效(始终为白色或透明,不能说出其中之一)。但是,如果我按Command-R(模拟界面),则该单元在模拟器中具有正确的背景色。

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

这可以解决问题:

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];

我在IB中设置所有布局/字体/背景素材。知道为什么在这种情况下不起作用吗?

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

这似乎是一个普遍的问题。有人可以指出正确的方向,以便(最终)理解在表格视图单元格中如何处理背景色。

最佳答案

There's an easier solution: When you create a UITableViewCell in Interface Builder, simply drag and drop an additional UIView so that it covers the entire UITableViewCell you're creating within IB. Place your additional UI elements on top of this additional UIView. You can set this extra UIView to whatever background you like.

There are quite a few answers on StackOverflow that suggest you change the background color of your UITableViewCell by using a line of code like this one:

cell.contentView.backgroundColor = [UIColor redColor];

If you add a drop shadow to your cell by adjusting the contentView's frame size slightly, you may find that this line will change both the background color of your cell and the color of your drop shadow area as well.

    公众号
    关注公众号订阅更多技术干货!