每5个细胞更改细胞背景

时间:2014-03-09 01:38:29

标签: ios objective-c uitableview colors

您好我想要改变我的UITableView Cells的5个单元格的颜色,所以对于单元格2,我将为绿色单元格一个蓝色,依此类推。然后,当我击中5个单元格时,我希望颜色重新开始。

这是我到目前为止所做的:

if(indexPath.row % 5 == 0){
    cell.backgroundColor = [UIColor blackColor];
} else  if (indexPath.row % 4 == 0) {
   cell.backgroundColor = [UIColor redColor];
} else  if (indexPath.row % 3 == 0) {
    cell.backgroundColor = [UIColor greenColor];
} else  if (indexPath.row % 2 == 0) {
    cell.backgroundColor = [UIColor blueColor];
} else if(indexPath.row % 1 == 0) {
    cell.backgroundColor = [UIColor orangeColor];

如果有人能指出我正确的方向,我会非常感激。谢谢!

2 个答案:

答案 0 :(得分:3)

你需要以相同的数字模数,而不是不同的数字。这应该指向正确的方向:

static NSArray* rowColors;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    rowColors = @[[UIColor redColor], [UIColor blueColor], [UIColor greenColor], [UIColor orangeColor], [UIColor yellowColor]];
});

int rowMod = indexPath.row % rowColors.count;

UIColor* color = rowColors[rowMod];

cell.contentView.backgroundColor = color;

这种方法比现有方法做得更好:

  • 它针对相同的数字执行%,这是您发布的内容中的核心逻辑问题
  • 它动态使用rowColors.count,以防您想要添加额外的颜色(例如,每7行而不是每5行更改一次)
  • 它使用数组,因此你没有if / else-if / else-if / else-如果失控
  • 它在cell.contentView上设置backgroundColor而不是cell,这是设置背景颜色的正确方法
  • 数组是静态的,只写一次,以确保良好的性能,并且每次设置单元格时都不会导致大量的内存分配

希望它有所帮助!

答案 1 :(得分:1)

我认为这就是你要找的东西:

if(indexPath.row % 5 == 0)
{
    cell.backgroundColor = [UIColor blackColor];
}
else  if (indexPath.row % 5 == 1)
{
   cell.backgroundColor = [UIColor redColor];
}
else  if (indexPath.row % 5 == 2)
{
    cell.backgroundColor = [UIColor greenColor];
}
else  if (indexPath.row % 5 == 3)
{
    cell.backgroundColor = [UIColor blueColor];
}
else if(indexPath.row % 5 == 4)
{
    cell.backgroundColor = [UIColor orangeColor];
}

你想保持模数除数相同 - 它实际上将要改变的余数

相关问题