用willDisplayCell改变TableViewCell颜色

来源:互联网 发布:js判断汉字长度 编辑:程序博客网 时间:2024/05/21 11:15

举个自己亲身经历的例子,一次为了改变UITableViewCell的颜色,开始时直接改变cell的backgroundColor,但发现搞不定,一番搜索后发现改变cell的ContenView的backgroundColor就OK了,不过一旦显示accessoryView就露馅了。于是乎干的彻底点,直接自定义一个UITableViewCell,并用一个UIImageView做背景,现在终于可以“为所欲为”了。不过回想下,怎么简单的一个问题如此大动干戈,真是不值当,所以心里会暗暗骂下Apple的工程师,怎么就不让cell的backgroundColor起作用呢?这么明显的bug!以至于以后的一段时间我就习惯用那“土办法”,而且是屡试不爽。突然有天在stackoverflow上看到一个类似问题的讨论,原来这种问题可以通过重写-tableView:willDisplayCell:forRowAtIndexPath:的委托方法实现。想想之前骂过的话以及走过的弯路,只能感叹自己掌握不深入。有了这样的经历后在遇到类似的问题我会先怀疑使用合理,而不是轻易下结论。

- (void)tableView: (UITableView*)tableView

  willDisplayCell: (UITableViewCell*)cell

forRowAtIndexPath: (NSIndexPath*)indexPath

{

    cell.backgroundColor = indexPath.row %2

    

    ? [UIColorcolorWithRed:234/255.0f green: 235/255.0fblue: 239/255.0f alpha: 1.0]

    

    : [UIColorcolorWithRed:226/255.0f green: 226/255.0fblue: 232/255.0f alpha: 1.0];

    

    cell.textLabel.backgroundColor = [UIColorclearColor];

    

    cell.detailTextLabel.backgroundColor = [UIColorclearColor];

    

}


原创粉丝点击