UITableViewCell checkmark to be toggled on and off when tapped

前端 未结 14 1476
执念已碎
执念已碎 2020-11-30 22:25

I\'m working on a tableview

I want to be able to tap on each cell and when tapped, it displays a checkmark on the cell

Now I have some code that makes this w

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 23:07

    The simple solution as others have pointed out would be to .checkmark the row in the didSelectRowAt method and set the row to .none in the didDeselectRowAtmethod as follow...

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    }
    

    But if you have a default row selected when the table loads you first need to deselect it when other rows are selected, in that case, use the code below instead in the didSelectRowAt method.

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        for row in 0..

提交回复
热议问题