在UITableViewCell中更改UILabel的背景颜色

rpj*_*rpj 11 cocoa-touch objective-c ios

UITableViewCell是"预先构建的",UILabel是您初始化后的唯一子视图.我真的想改变所说标签的背景颜色,但无论我做什么,颜色都不会改变.有问题的代码:

UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;
Run Code Online (Sandbox Code Playgroud)

Ben*_*ieb 8

你的代码片段对我来说很好,但必须在将单元格添加到表格并显示之后完成,我相信.如果从中调用initWithFrame:reuseIdentifier:,则会出现异常,因为尚未创建UILabel 子视图.

可能最好的解决方案是添加您自己的UILabel,按照您的标准配置,而不是依赖于内置的这条(非常摇摇晃晃的)路径.


Tom*_*ift 5

这不起作用,因为UITableViewCell在layoutSubviews方法中设置其标签backgroundColors.

如果要更改内置textLabel或detailTextLabel的颜色,请为UITableViewCell创建子类并覆盖layoutSubviews.调用超级实现,然后将backgroundColor属性更改为您想要的.

- (void) layoutSubviews
{   
     [super layoutSubviews];

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