UITableView单元格背景颜色

Sha*_*med 20 iphone

如何为UITableView中的单元格设置不同的背景颜色(特别是七个单元格的彩虹色)

alb*_*amg 83

设置backgroundColor属性:

cell.backgroundColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

注意,必须在tableView:willDisplayCell:forRowAtIndexPath:方法中设置backgroundColor (来自UITableViewCell引用):

注意:如果要更改单元格的背景颜色(通过UIView声明的backgroundColor属性设置单元格的背景颜色),则必须在tableView中执行此操作:willDisplayCell:forRowAtIndexPath:委托方法而不是tableView :cellForRowAtIndexPath:数据源.组样式表视图中单元格背景颜色的更改在iOS 3.0中具有与以前版本的操作系统不同的效果.它现在影响圆角矩形内的区域而不是它外面的区域.

使用indexPath参数实现彩虹效果.

  • 有一些模糊的情况,其中willDisplayCell不会被调用,与从详细视图返回而不是重新加载表有关. (2认同)

gam*_*zii 9

如果要根据实际单元格数据对象中的某些状态设置单元格颜色,则这是另一种方法:

如果将此方法添加到表视图委托:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = cell.contentView.backgroundColor;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的cellForRowAtIndexPath方法中,您可以执行以下操作:

if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
    cell.contentView.backgroundColor = [UIColor blueColor];
}
Run Code Online (Sandbox Code Playgroud)

这样可以节省在willDisplayCell方法中再次检索数据对象的麻烦.


小智 1

很确定 UITableViewCell 是 UIView 的子类,所以:

cell.backgroundColor = [UIColor blueColor];
Run Code Online (Sandbox Code Playgroud)

对于可怕的彩虹色,这里有一个例子:

static NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], etc..., nil];
cell.backgroundColor = [colors objectAtIndex:indexPath.row];
Run Code Online (Sandbox Code Playgroud)