我正在尝试为子类 UITableViewCell
设置背景色。我知道通常我应该使用 tableView:willDisplayCell:forRowAtIndexPath:
。但是,我有一些逻辑可以自定义 tableView:cellForRowAtIndexPath:
中 UITableViewCell
的几个方面,并且我想根据该逻辑设置单元格的背景颜色。我是否必须在 tableView:willDisplayCell:forRowAtIndexPath:
中复制 tableView:cellForRowAtIndexPath:
中的整套条件才能设置背景颜色?这种代码重复似乎很浪费,而且可能不明智。
我能想到的最好的解决方案是向 UITableViewCell
子类添加一个 UIColor 属性,根据那里的条件在 tableView:cellForRowAtIndexPath:
中设置它,然后就可以了让 tableView:willDisplayCell:forRowAtIndexPath:
将单元格的背景颜色设置为它自己的颜色属性。这是处理这种情况的正确方法吗?看起来有点笨拙,但我想不出更好的东西。
最佳答案
您可以创建返回适当颜色的函数并相应地设置它
-(UIColor*)getColorForIndexPath:(NSIndexPath*){
UIColor *cellColor=nil;
//Do whatever your logic is for finding appropriate color assign to cellColor
return cellColor;
}
现在使用这个函数来设置color as,所以你只需要修改一个地方就可以在两个地方都生效。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
.... //Your code for cell
cell.backgroundColor = [self getColorForIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
.... //Your code for cell
cell.backgroundColor = [self getColorForIndexPath:indexPath];
}
注意:如果您只放置在任何委托(delegate)方法中,这仍然有效,因此无需在 2 个地方调用。
关于ios - UITableViewCell 的条件背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346336/