在 Swift 的 UITableView 中设置选中/未选中视图颜色

Set Selected/ Unselected view color in UITableView in Swift

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

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

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

我无法重置之前的单元格。

您需要override setSelected(_:animated:)方法TableViewCell并根据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

您可以使用 deselectRow tableView 的功能:

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

希望对您有所帮助...

根据 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)
}