首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每5个细胞改变一次细胞背景

每5个细胞改变一次细胞背景
EN

Stack Overflow用户
提问于 2014-03-09 01:38:28
回答 2查看 82关注 0票数 1

你好,我想改变我的UITableView细胞的颜色,以前的5单元,所以我将有绿色的单元格1蓝色的单元格2等等。然后,一旦我击中5个单元格,我希望颜色重新开始。

到目前为止,这就是我所拥有的:

代码语言:javascript
复制
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];

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-09 02:24:12

我想这就是你要找的:

代码语言:javascript
复制
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];
}

你想要保持模数除数不变--它的剩余部分实际上是要改变的。

票数 1
EN

Stack Overflow用户

发布于 2014-03-09 02:27:34

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

代码语言:javascript
复制
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/ out如果失控了
  • 它将backgroundColor设置在cell.contentView上而不是单元格上,这是设置背景色的正确方法。
  • 该数组是静态的,只写入一次,以确保良好的性能,并且不会在每次设置单元格时导致大量内存分配。

希望能帮上忙!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22277383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档