在iPhone上设置表格视图单元格的背景颜色

eba*_*unt 35 iphone

我想达到这样的效果,其中表视图的一个单元格将具有蓝色背景,下一个将具有白色,下一个将再次具有蓝色,然后是白色等等...您能告诉我我该怎么办?去做?

谢谢.

jes*_*rry 73

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

#pragma mark UITableViewDelegate
- (void)tableView: (UITableView*)tableView 
  willDisplayCell: (UITableViewCell*)cell 
forRowAtIndexPath: (NSIndexPath*)indexPath
{
    cell.backgroundColor = indexPath.row % 2 
        ? [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0] 
        : [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}
Run Code Online (Sandbox Code Playgroud)

  • +1这是有效的,是我可以将textLabel.backgroundColor设置粘贴的唯一方法.在tableView:cellForRowAtIndexPath中设置它:对我来说不起作用(OS 3.2)但是这样做了. (3认同)
  • 有一个旧的WWDC视频,从2009年或2010年,涵盖了这一点.表视图将调整背景以管理单元格的选择状态,这就是为什么唯一可以可靠地修改它的地方是willDisplayCell方法. (2认同)

los*_*sit 43

您必须设置单元格内容视图的背景颜色

cell.contentView.backgroundColor = [UIColor colorWithRed...]
Run Code Online (Sandbox Code Playgroud)

这将设置整个单元格的背景.

要为备用单元格执行此操作,请使用indexPath.row%by 2.

  • 如果使用cell.backgroundColor,您将得到蓝色/橙色的结尾.如果使用cell.contentView.backgroundColor,则整个单元格将被着色,除非您的单元格(如标签)中有任何具有白色背景的控件.在这种情况下,您还必须更改其背景颜色.否则,contentView.backgroundColor方法一直对我有用. (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方法中再次检索数据对象的麻烦.


小智 6

请在cellForRowAtIndexPath中添加以下代码

if (indexPath.row % 2 == 0){
    cell.backgroundColor =[UIColor blueColor];
} else {
    cell.backgroundColor =[UIColor whiteColor];
}
Run Code Online (Sandbox Code Playgroud)

我认为这对您有帮助