我使用的是一个UITableView,当我使用didSelectRow函数在cellForRowAt上点击单元格时,我正在改变单元格的颜色。困扰我的是,当我向下滚动或向上滚动时,我之前改变颜色的那些细胞被改变为其他细胞。这是我的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = .white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = myTableView.cellForRow(at: indexPath) as! TasksTableViewCell
cell.backView.backgroundColor = UIColor(named: "primaryViewColor")
} 有人知道为什么会这样吗?有没有人有一个解决方案,当只有那些细胞改变颜色时,我点击,而当我滚动或向上,只有这些细胞有另一种颜色?
发布于 2022-01-06 09:43:53
TableViewCells一离开可见区域就会被重用。这意味着,当视图层次结构向上或向下滚动时,其背景颜色的单元格将被删除。如果再次滚动相应的行,则该IndexPath再次调用函数IndexPath,该单元格将得到一个白色的背景。
最简单的方法是保存所选单元格的IndexPaths,并在必须选择当前单元格时签入cellForRowAt函数。
将以下变量添加到viewController类中:
var selectedIndexPaths = Set<IndexPath>()并修改tableView委托方法:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = myTableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = (selectedIndexPaths.contains(indexPath) ? UIColor(named: "primaryViewColor") : .white)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedIndexPaths.contains(indexPath)
{
selectedIndexPaths.remove(indexPath)
}
else
{
selectedIndexPaths.insert(indexPath)
}
tableView.reloadRows(at: [indexPath], with: .none)
}https://stackoverflow.com/questions/70604868
复制相似问题