当我滚动时,TableView DidSelectRowAt 会改变其他单元格的背景颜色

TableView DidSelectRowAt will change background colors of other cells when I scroll

我有一个 TableView 有时有足够的单元格允许我滚动 table。同时我设置了我的 didSelectRow 来切换单元格的背景颜色。似乎选择了一些然后向下滚动我发现更多的单元格已经超出了我的控制范围。

这是我的 didSelectRowAt:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   packSizesTableView.cellForRow(at: indexPath)?.backgroundColor = UIColor.yellow
   packList[indexPath.row].picked = true
   pickedRows.append(indexPath)

如果 indexPath.row,除了更改颜色之外,还有其他方法可以选择我的 table 单元格吗?

您可以在 cellForRowAt 方法中设置单元格颜色,如下所示:-

If packList[indexPath.row].picked {
    yourCell.backgroundColor = UIColor.yellow 
}  else {
    yourCell.backgroundColor =  UIColor.red
}

简短回答:您看到错误的单元格颜色发生变化,因为单元格被重复使用,并且您需要在重复使用单元格时将颜色设置为正确的选项。

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 方法中,您可以检查 packList 数组以查看是否需要选择要出队的单元格并在那里设置颜色。这将处理正在创建新单元格的情况 以及 正在重用的单元格。

if packList[indexPath.row].picked {
  cell.backgroundColor = UIColor.selectedColor
} else {
  cell.backgroundColor = UIColor.defaultColor
}

您有多个处理选项 selecting/deselecting,因此这里是一个选项。在 tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 你可以简单地做:

packList[indexPath.row].picked = !packList[indexPath.row].picked
tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.whateverYouWant)

您也可以只更新您的 packList 数组(cellForRow 需要它),并覆盖单元格的 func setSelected(_ selected: Bool, animated: Bool) 方法中的逻辑。