0

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

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

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

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

4

3 回答 3

5

只需使用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]您想要的任何数值。

于 2013-08-10T18:08:28.813 回答
2

尝试这个:

    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];
}
于 2013-08-10T18:15:58.770 回答
2

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

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;
}
于 2013-08-10T18:14:07.243 回答