【问题标题】:Change Cell Background Every 5 Cells每 5 个单元格更改单元格背景
【发布时间】:2014-03-09 01:38:28
【问题描述】:

您好,我想将 UITableView 单元格的颜色更改为 5 个单元格,因此单元格 1 的颜色为绿色,单元格 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];

如果有人能指出我正确的方向,我将不胜感激。谢谢!

【问题讨论】:

  • 到目前为止你得到了什么结果?您的代码看起来类似于我为您的想法实施的代码。您是否尝试过将此代码放入-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cel forRowAtIndexPath:(NSIndexPath *)indexPath?另外,只是一个想法,但我会将逻辑按相反的顺序排列,因为行“4”(棕色)将始终通过“2”分支(黑色)。或者,您可以执行int row = indexPath.row % 5;,然后根据该值执行您的if/else/then 块。
  • 我现在拥有的颜色每隔一个单元格重复一次。我会尝试并回复你。
  • 我猜你的意思是所有其他单元格都是黑色的,对吧?根据您的逻辑的逻辑处理顺序,这完全有意义! ;-) 我希望:1)黑色,2)未定义(可能是白色作为默认背景),3)黑色,4)白色,5)黑色,6)蓝色等......
  • 是的,这就是我的意思,我目前正在修复逻辑 ;-) 它看起来已经更好了。
  • 好的,这就是我现在所拥有的,它仍然无法按顺序打印。我在问题中更新了它。

标签: ios objective-c uitableview colors


【解决方案1】:

您需要对相同的数字取模,而不是不同的数字。这应该为您指明正确的方向:

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-if 失控
  • 它在 cell.contentView 而不是 cell 上设置 backgroundColor,这是设置背景颜色的正确方法
  • 该数组是静态的并且只写入一次,以确保良好的性能并且不会在每次设置单元时导致大量内存分配

希望对你有帮助!

【讨论】:

  • 优秀的答案。 (已投票)
【解决方案2】:

我想这就是你要找的东西:

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];
}

您希望模数除数保持不变——余数实际上会发生变化

【讨论】:

  • 检查我的答案,我相信它会好一些,因为没有太多的 if/else 失控,它还使用cell.contentView.backgroundColor 而不是cell.backgroundColor
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多