【问题标题】:Alternate between 3 colors in UITableviewCell在 UITableviewCell 中的 3 种颜色之间交替
【发布时间】:2013-08-12 10:55:18
【问题描述】:

我有一个 UITableView,我想以 3 种不同的背景颜色显示。基本上是白色、浅灰色、深灰色,然后再回到白色等等。

到目前为止,这是我在堆栈溢出中所能找到的全部内容:

if (indexPath.row % 2) {
        cell.contentView.backgroundColor = [UIColor lightGrayColor];
    } else {
        cell.contentView.backgroundColor = [UIColor darkGrayColor];
}

这适用于 2 种颜色。如何在 3 种颜色之间切换?

【问题讨论】:

    标签: ios uitableview background-color


    【解决方案1】:

    只需使用3 而不是2,然后相应地设置值,例如:

    NSInteger colorIndex = indexPath.row % 3;
    
    switch (colorIndex) {
        case 0:
            cell.contentView.backgroundColor = [UIColor whiteColor];
            break;
        case 1:
            cell.contentView.backgroundColor = [UIColor lightGrayColor];
            break;
        case 2:
            cell.contentView.backgroundColor = [UIColor darkGrayColor];
            break;
    }
    

    如果您想要更多的灰色阴影(例如 50),您也可以将 [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] 与您想要的任何数值一起使用。

    【讨论】:

    • 工作就像一个魅力,你是第一个回答。谢谢!
    【解决方案2】:

    Rob 是正确的,但我会使用UIColor 提供的default color

    NSInteger colorIndex = indexPath.row % 3;
    
    switch (colorIndex) {
        case 0:
            cell.contentView.backgroundColor = [UIColor whiteColor];
            break;
        case 1:
            cell.contentView.backgroundColor = [UIColor lightGrayColor];
            break;
        case 2:
            cell.contentView.backgroundColor = [UIColor darkGrayColor];
            break;
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

          if(indexPath.row % 3 ==0){
            cell.contentView.backgroundColor = [UIColor whiteColor];
      }
          if((indexPath.row-1) % 3 ==0){
            cell.contentView.backgroundColor = [UIColor lightGrayColor];
      }
      
          if((indexPath.row - 2) % 3 ==0){
            cell.contentView.backgroundColor = [UIColor darkGrayColor];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-19
        • 2017-12-28
        • 1970-01-01
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-06
        相关资源
        最近更新 更多