【问题标题】:Make cell background color different for each object in array使数组中每个对象的单元格背景颜色不同
【发布时间】:2014-12-05 05:17:22
【问题描述】:

我想将表格视图中每一行的背景颜色更改为不同。例如,我的数组是 3,2,1。如果第一行等于我的“总数”(3)我想要它是红色的,如果第二行是我的“总数”中的负1(3)我想要它蓝色......因为我有下面的代码我是只有满足条件才能更改整个 tableview 的颜色。

if ([myArray containsObject:total]) {     
        cell.backgroundColor = [UIColor redColor];
        }

    else if ([myArray containsObject:totalMinusOne]) {
        cell.backgroundColor = [UIColor blueColor];
        }

如何更改每个单元格的背景并使其依赖于 if/else 语句?

【问题讨论】:

  • 每个单元格的总数实际上不同吗?你设置断点检查了吗?

标签: ios uitableview nsarray background-color


【解决方案1】:

您需要设置单元格的 ContentView 背景颜色。

[cell.contentView setBackgroundColor:[UIColor blueColor]];

【讨论】:

  • 我尝试替换它,但单元格颜色的作用相同,但沿边是垂直的。
  • 单元格顶部是否还有其他视图。
  • 可能您的内容视图上有标签。您需要将其他视图背景设置为 [UIColor clearColor]。
【解决方案2】:

这里有你需要的-

为此使用UITableView委托方法:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            [cell setBackgroundColor:[UIColor redColor]];
            break;

        case 1:
            [cell setBackgroundColor:[UIColor greenColor]];
            break;

        case 2:
            [cell setBackgroundColor:[UIColor blueColor]];
            break;

        default:
            break;
    }
}

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 2017-03-11
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2022-12-12
    相关资源
    最近更新 更多