首页 > 解决方案 > UITableViewCell 设置 contentView backgroundColor 多于一个section

问题描述

在 UITableView 的 didSelectRow 方法中,我正在更改 UITableViewCell 的 contentView.backgroundColor ,但我有 2 个部分,当我使用以下内容投射单元格时:

let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)! 并设置selectedCell.contentView.backgroundColor代码更改两个部分的背景颜色。如何仅从 中投射单元格indexPath.section

更新来自@rmaddy 的回答

当我在 didSelectRow 方法中保存变量 indexPath.row 和 indexPath.section 并使用 willDisplay 单元格或 cellForRow 中的变量来设置 backgroundColor 时,它会在每 8-16-32-64 行上自动设置 backgroundColor。

更新 2:在 cellForRow 我设置这个:

    if(indexPath.row == selectedFromIndex && indexPath.section == selectedFromSection){
        cell.contentView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.1)
    }else{
        cell.backgroundColor = .clear
        cell.isSelected = false
    }

selectedFromIndex 和 selectedFromSection 是保存在 didSelectRowMethod 中的变量。选择仍然出现在第 8-16-32-64 行...

标签: swiftuitableviewcasting

解决方案


这与铸造无关。您只需要一份if声明来检查该部分。

if indexPath.section == 0 { // 1 depending on which section you need
    // get the cell and set the background color
}

但这会随着用户滚动而失败。您应该做的didSelectRow是更新您的数据模型以跟踪已选择哪些行以及哪些行应该获得不同的颜色背景,然后告诉表视图重新加载该行。

然后cellForRowAt(或willDisplay:forRowAt:)中的代码应使用该数据根据需要设置单元格的颜色。

无论您使用哪种方法,请确保根据需要设置或重置背景颜色,因为行被重用:

// pseudo code:
if row is selected {
    cell.backgroundColor = .someSelectedColor
} else {
    cell.backgroundColor = .someUnselectedColor
}

推荐阅读