无法准确设置单元格背景和文本颜色



我需要将表格单元格的背景设置为特定的颜色。(#222222或RGB(32,32,32)分别)

IB中table view的背景设置正确。正确的灰色出现在表标题的背面和部分标题等。但我与细胞斗争。

要自定义单元格的外观,我子类UITableCell并实现layoutSubviews方法。

- (void)layoutSubviews {
    [super layoutSubviews];
    self.selectionStyle                 = UITableViewCellSelectionStyleGray;
    self.backgroundColor                = [UIColor darkGrayColor];
    self.contentView.backgroundColor    = [UIColor darkGrayColor];
    self.textLabel.textColor            = [UIColor whiteColor];
    self.detailTextLabel.textColor      = [UIColor grayColor];
}

然而,grayColor和darkGrayColor根本不匹配我需要的颜色。

我很自然地尝试了UIColor的colorWithRed:green:blue:alpha方法。

- (void)layoutSubviews {
    [super layoutSubviews];
    self.selectionStyle                 = UITableViewCellSelectionStyleGray;
    self.backgroundColor                = [UIColor colorWithRed:(32/256) green:(32/256) blue:(32/256) alpha:1];
    self.contentView.backgroundColor    = [UIColor colorWithRed:(32/256) green:(32/256) blue:(32/256) alpha:1];
    self.textLabel.textColor            = [UIColor whiteColor];
    self.detailTextLabel.textColor      = [UIColor colorWithRed:(32/256) green:(32/256) blue:(32/256) alpha:1];
}

结果是黑色背景和黑色的detailTextLable。(当然,对背景和文本标签使用相同的颜色是没有意义的。我只是想弄清楚colorWithRed:green:blue:alpha做什么,不做什么。

与普通样式表我很好。这些单元格根本没有背景颜色。当我省略设置backgroundColor和contentView的backgroundColor属性时,单元格的背景显示为定义为IB中的表的背景色。但与分组表的标准背景是一些浅灰色,我想改变一些更体面的颜色,以匹配我的客户的风格指南。

我做错了什么?我是否正确使用colorWithRed:green:blue:alpha ?

任何建议都非常感谢。

我会尝试其他方法来计算颜色浮动:

[UIColor colorWithRed:(32.0f/255.0f) green:(32.0f/255.0f) blue:(32.0f/255.0f) alpha:1.0f];

因为0也包含,所以你有0到255的值,而不是1到256的值。

如果你想让单元格透明使用[UIColor clearColor]

32/256 = 0 but 32/256.0 = 0.125 .

感谢您指出错误。

然而,这并不能完全回答与普通表样式和分组表样式之间的差异有关的问题。

以防有人觉得这个问题很有趣:

  1. 分组样式带有背景视图。我把它设为nil。
  2. 分组样式总是有一个单元格背景色设置的东西。因此省略self.backgroundColor=…表述不充分。
最后

self.backgroundColor            = [UIColor clearColor];

做到了。这与我所犯的objective-c错误毫无关系。

最新更新