如何在 swift 的 tableView 中向左滑动更改单元格颜色

How to change cell color on swipe left in tableView in swift

我在 tableview 中有 3 个操作按钮,我想在滑动时更改当前单元格的背景颜色,如果我滑动另一个单元格,预选单元格应该恢复,只有当前单元格的背景颜色应该更改。我正在使用 trailingSwipeActionsConfigurationForRowAt 委托进行滑动操作,但我不知道如何更改当前滑动单元格的背景颜色,任何想法请帮助我。

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let viewButton = UIContextualAction(style: .normal, title: "") {  (contextualAction, view, boolValue) in
            // View action
            print("View action")
            
        }
        viewButton.backgroundColor = .gray
        viewButton.image = UIImage(named: "view")
    
        //Approve
    
        let approveButton = UIContextualAction(style: .normal, title: "") {  (contextualAction, view, boolValue) in
            // Approve action
            print("Approve action")
            
        }
        approveButton.backgroundColor = .gray
        approveButton.image = UIImage(named: "accept")
    
    
        //Reject
    
        let rejectButton = UIContextualAction(style: .normal, title: "") {  (contextualAction, view, boolValue) in
            // Reject action
            print("Reject action")
            
        }
        rejectButton.backgroundColor = .gray
        rejectButton.image = UIImage(named: "reject")
    

        var swipeActions = UISwipeActionsConfiguration(actions: [rejectButton, approveButton, viewButton])
        
        swipeActions.performsFirstActionWithFullSwipe = false
        return swipeActions
   }

实现数据模型的方式有上百万种。只是给你一个想法,你可以改变你可以使用的 tableViewCell 背景颜色 tableView.cellForRow(at: indexPath:

var selectedCell:IndexPath? //this hold the index path of the selected cell 

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
   
    // your code here .....

    if let cell = tableView.cellForRow(at: indexPath) {
            if selectedCell == nil {
                print("selected cell is nil")
                //first selection
                cell.backgroundColor = .red
                selectedCell = indexPath
                
            }else{
                if tableView.indexPath(for: cell) != selectedCell {
                    // you are selecting another cell
                    cell.backgroundColor = .red
                    tableView.cellForRow(at: selectedCell!)?.backgroundColor = nil
                    selectedCell = indexPath
                }
            }
      }
}
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.contentView.backgroundColor = .red

}

func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    if indexPath != nil {
        let cell = tableView.cellForRow(at: indexPath!)
        cell?.contentView.backgroundColor = .red
    }
    
}