Changing background color of selected cell?

后端 未结 30 2962
太阳男子
太阳男子 2020-11-29 00:22

Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 00:42

    var last_selected:IndexPath!
    

    define last_selected:IndexPath inside the class

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! Cell
        cell.contentView.backgroundColor = UIColor.lightGray
        cell.txt.textColor = UIColor.red
    
        if(last_selected != nil){
            //deselect
            let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
            deselect_cell.contentView.backgroundColor = UIColor.white
            deselect_cell.txt.textColor = UIColor.black
        }
    
        last_selected = indexPath
    }
    

提交回复
热议问题