我使用的是一个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:35:25
每次显示单元格时都会调用cellForRowAt。您需要选择列表来保存选定的索引。
var listSelected: [Int] = []和
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = listSelected.contains(indexPath.row) ? UIColor(named: "primaryViewColor") : .white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if listSelected.contains(indexPath.row) {
listSelected = listSelected.filter{$0 != indexPath.row}
} else {
listSelected.append(indexPath.row)
}
tableView.reloadRows(at: [indexPath], with: .automatic)
}发布于 2022-01-06 09:52:14
我遇到过你见过很多次的问题吗?即使使用和iVar可以解决问题,您是混合“控制器”逻辑和“模型”逻辑。
我通常更喜欢在模型中移动“选择”状态。假设您有一个类"Contact“用来填充单元数据(通常的MVC模式),我添加如下:
class contact{
..
var selected = false
}在用于应用选择的TV委托方法中,或者更好的是,我在自定义单元格中使用自定义选择方法(例如,在单元格中查看√元素)作为免费的多个选择,您还可以将当前的选择保存到下一次运行:)
发布于 2022-01-06 09:24:07
因此,据我所知,您选择了一个单元格,在此之后,其他单元格看起来像是被选中的?
如果是这样的话,我认为这是因为您改变了单元格的背景色,而tableViews和collectionViews正在重用这些单元格,基本上将您更改的背景保持在后面。
https://stackoverflow.com/questions/70604868
复制相似问题