【问题标题】:cell.backgroundColor not responding if set at tableView:cellForRowAtIndexPath如果在 tableView:cellForRowAtIndexPath 设置 cell.backgroundColor 没有响应
【发布时间】:2012-02-08 09:01:31
【问题描述】:

我正在尝试用红色为某些表格行着色,所以我尝试添加

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
... init Code here
cell.backgroundColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

配件的复选标记出现但不是红色。

我后来发现通过将它放在 tableView:willDisplayCell 中它可以工作。这是设计使然吗?为什么它忽略了我在初始化单元格时已经设置的值?

【问题讨论】:

    标签: ios cocoa-touch uitableview background-color


    【解决方案1】:

    仅供参考,Ravi 的回答是正确的,但如果您想简化实现,也可以设置单元格的 contentView 背景颜色以达到相同的效果。

    cell.contentView.backgroundColor = [UIColor redColor];

    这不是记录在案的解决方案,但以下方法可行:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ... init Code here
        cell.contentView.backgroundColor = [UIColor redColor];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    

    【讨论】:

      【解决方案2】:

      单元格的外观在tableView:willDisplayCell 中自定义。因此,要回答您的问题,是的,这是设计使然。单元格的contentView 的附属视图和子视图需要在cellForRowAtIndexPath 中修改/分配。

      来自tableView:willDisplayCell:forRowAtIndexPath:的文档:

      表格视图在使用单元格绘制一行之前将此消息发送给其委托人,从而允许委托人在单元格对象显示之前对其进行自定义。此方法使委托有机会覆盖先前由表视图设置的基于状态的属性,例如选择和背景颜色。代理返回后,表格视图仅设置 alpha 和 frame 属性,然后仅在为滑入或滑出的行设置动画时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2017-01-10
        • 1970-01-01
        相关资源
        最近更新 更多