UITableViewCell checkmark to be toggled on and off when tapped

前端 未结 14 1439
执念已碎
执念已碎 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条回答
  • 2020-11-30 23:13

    Swift 5.0

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    
        if let cell = tableView.cellForRow(at: indexPath) {
            resetChecks()
            cell.accessoryType = .checkmark
        }
    }
    
    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
    }
    
    func resetChecks() {
        for i in 0..<tableView.numberOfSections {
            for j in 0..<tableView.numberOfRows(inSection: i) {
                if let cell = tableView.cellForRow(at: IndexPath(row: j, section: i)) {
                    cell.accessoryType = .none
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 23:14

    I have used tableView(_:didSelectRowAt:), delegate method to accomplish this feature of putting check mark on the cell and removing it when the cell is tapped again. Here is the code:

    //MARK:-create delegate methode that is fired when a cell is clicked
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         tableView.deselectRow(at: indexPath , animated: true)
    
    
         if  let cell = tableView.cellForRow(at: indexPath){
             if cell.accessoryType == .checkmark {
                 cell.accessoryType = .none
             }
             else {
                 cell.accessoryType = .checkmark
             }
         }
         
         
     }
    
    0 讨论(0)
提交回复
热议问题