UITableViewCell上的textLabel.backgroundColor不起作用

Tom*_* B. 13 cocoa-touch uitableview

我正在尝试设置我的UITableViewCells的标签backgroundColor,它什么都没做.我想知道是否有另一种方法可以做到这一点,所以我问!

我试过这个:

    cell.textLabel.backgroundColor = [UIColor redColor];
cell.backgroundColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

它不起作用,其他什么?

谢谢!

小智 45

我假设你在cellForRowAtIndexPath中尝试这个.

根据UITableViewCell类引用:

注意:如果要更改单元格的背景颜色(通过UIView声明的backgroundColor属性设置单元格的背景颜色),则必须在tableView中执行此操作:willDisplayCell:forRowAtIndexPath:委托方法而不是tableView :cellForRowAtIndexPath:数据源.

这样做:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.textColor = [UIColor yellowColor]; //can do here OR in cellForRowAtIndexPath
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更精细地控制单元格显示,一种简单的方法是在IB中设计它并从cellForRowAtIndexPath中的nib加载它.请参阅"装入自定义表视图细胞笔尖文件"一节本页面表视图编程指南中.