【问题标题】:Set Selected/ Unselected view color in UITableView in Swift在 Swift 的 UITableView 中设置选定/未选定的视图颜色
【发布时间】:2020-05-22 08:59:18
【问题描述】:

我有一个表格视图,所有视图都将具有清晰的颜色。当用户选择一个单元格时,我需要将选定的 tableview 单元格设为红色并重置所有其他先前的单元格以清除颜色。 如何管理单元格的状态,无论它是否被选中。

我正在使用此代码更改所选索引的颜色。

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell:TableViewCell = tableView.cellForRow(at: indexPath) as?  TableViewCell else { return }
    cell.backgroundColor = UIColor.red
}

我无法重置前一个单元格。

【问题讨论】:

  • 可以使用自定义单元格来设置选中和未选中的UI

标签: ios swift uitableview selection


【解决方案1】:

根据 PGDev 的回答,您需要视图控制器中的一个属性来保留选定的索引路径

var selectedIndexPath : IndexPath?

如果没有选择行,则属性为nil


cellForRow添加一行来管理选择

cell.isSelected = indexPath == selectedIndexPath

didSelectRowAt 中将刚刚选择的索引路径与selectedIndexPath 进行比较,更新selectedIndexPath 并相应地重新加载行。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var pathsToReload = [indexPath]
    if let selectedPath = selectedIndexPath {
        if indexPath == selectedPath { // deselect current row
            selectedIndexPath == nil
        } else { // deselect previous row, select current row
            pathsToReload.append(selectedPath)
            selectedIndexPath = indexPath
        }
    } else { // select current row
        selectedIndexPath == indexPath
    }
    tableView.reloadRows(at: pathsToReload, with: .automatic)
}

【讨论】:

    【解决方案2】:

    你可以使用deselectRow func of tableView :

    func deselectRow(at indexPath: IndexPath, 
        animated: Bool){
        guard let cell:TableViewCell = tableView.cellForRow(at: indexPath) as?  TableViewCell else { return }
    cell.backgroundColor = UIColor.clear
    }
    

    希望对你有帮助...

    【讨论】:

      【解决方案3】:

      您需要在TableViewCell 中使用override setSelected(_:animated:) 方法,并根据selected 状态配置backgroundColor

      class TableViewCell: UITableViewCell {
          override func setSelected(_ selected: Bool, animated: Bool) {
              super.setSelected(selected, animated: animated)
              self.backgroundColor = selected ? .red : .clear
          }
      }
      

      无需更改tableView(_:didSelectRowAt:) method 中的backgroundColor

      【讨论】:

      • 实际上我还需要管理单元格选择上的按钮操作。 @PGDev
      • @ios 按钮操作?请澄清。
      • 我正在创建一个测验应用程序,用户将在其中选择一个答案,然后单击下一步按钮转到下一个问题。
      • 会在setselected函数中添加?
      猜你喜欢
      • 2016-02-02
      • 2014-10-21
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多