【问题标题】:TableView DidSelectRowAt will change background colors of other cells when I scroll当我滚动时,TableView DidSelectRowAt 将更改其他单元格的背景颜色
【发布时间】:2019-11-18 17:38:29
【问题描述】:

我有一个 TableView 有时有足够的单元格允许我滚动表格。同时我设置了我的 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 的颜色之外,我还有其他选择表格单元格的方法吗?

【问题讨论】:

  • 你应该覆盖UITableView单元格中的setSelected(_:animated:)并在那里设置颜色。
  • 您是否希望每个单元格在被选中时都改变颜色,然后从那时起保持该颜色?还值得解释一下您是如何注册/创建/重用 tableView 单元格的,因为随机着色听起来像是这个领域的一个问题。

标签: swift xcode uikit tableview


【解决方案1】:

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

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

【讨论】:

  • 这是正确的答案,但可以使用一些解释。因为单元格是排队和回收的,所以当您向上和向下滚动时,您设置背景颜色的同一个单元格将在不同的位置重新使用。每次分配单元格时,您都需要在 cellForRowAt 中重置此类条件以避免该问题。为此,您应该为任一条件设置颜色,就像 @Nexus 在此处所做的那样。
【解决方案2】:

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

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

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

您有多种处理选择/取消选择的选项,所以这里有一个选项。在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) 方法中的逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2020-05-26
    相关资源
    最近更新 更多