Search code examples
iosswiftuikittableview

Update count when i deselected cell


I have counter which show number of selected cell, i wanna update this number when i deselected cell, this my code:

CustomTableViewCell:

override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        if(selected) {
            self.selectionStyle = .none
            self.shadowView.isHidden = false
            self.checkboxBtn.isHidden = false
        } else {
            self.shadowView.isHidden = true
            self.checkboxBtn.isHidden = true
        }
    }

ViewController with tableview(this func show number selected cell):

 func updateCount() {
        if let list = usersTableView.indexPathsForSelectedRows as? [IndexPath] {
            usersNumber.text = String(list.count)
        }
    }

UITableViewDelegate:

extension UsersController: UITableViewDelegate {
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            if let cell = self.usersTableView.cellForRow(at: indexPath) as? UsersTableViewCell {
                cell.checkboxBtn.isHidden = false
                cell.shadowView.isHidden = false
                cell.selectionStyle = .none
                updateCount()
            }
        }
    }

if i deselected cell, number on counter remains the same.


Solution

  • Please use delegate method tableView(_:didDeselectRowAt):

    extension UsersController: UITableViewDelegate {
            func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
                    updateCount()
              
            }
        }