2

我的项目中有一个 UITableView 控制器。所以我做了一个 UITableViewCell 设置,如下所示:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)."

    if indexPath.row % 2 == 1 {
        cell.backgroundColor = UIColor.gray
    }

    return cell
}

如果它们的索引不能被 2 整除,我希望我的 tableview 的单元格是灰色的。

当tableview出现时,一切都完美了!但是当我上下滚动时,单元格开始将颜色变为灰色。

所以最后我所有的细胞都是灰色的。

以下是一些图片:

4

3 回答 3

4

尝试添加一个else语句,因为单元格被重复使用。

else {
    cell.backgroundColor = UIColor.white
}
于 2016-10-16T12:11:37.143 回答
2

问题是您从未将背景设置回白色。由于单元格被重复使用,因此在某些时候您将所有单元格设置为灰色。相反,您应该在每次重用单元格时检查行索引:

cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.white : UIColor.gray
于 2016-10-16T12:14:58.460 回答
0

因为 tableview 重用了单元格

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)."

if indexPath.row % 2 == 1 {
    cell.backgroundColor = UIColor.gray
}else{
    cell.backgroundColor = YOUR_COLOR
}
return cell

}

编辑:Gellert Lee 首先回答了这个问题,而且非常简单

于 2016-10-16T12:13:43.727 回答