skip to Main Content

What I expect to happen when I click on a row: the text from the row gets printed instantly, the grey background flashes, the checkmark comes on/off instantly.

What actually happens: the text doesn’t print until I click on a different row, the grey background doesn’t flash, the checkmark only updates when I click on a different row.

enter image description here

let itemArray = ["Find Mike", "Buy Eggos", "Destroy Demagorgon"]

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    
    print(itemArray[indexPath.row])
    
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
}

I can’t tell why this isn’t working the way I expect. I used print statements to check when the function was getting called, but I can’t get past the fact that it just isn’t calling when I expect it to.

Answer

It was a syntax error, I was using didDeselectRowAt rather than didSelectRowAt.

3

Answers


  1. I think it would be a better approach to simply toggle the state in your model. Add a flag to your model class that represents the current state.

    Then in your didDeselectRowAt set the flag and call tableView.reloadItems with the clicked indexPath.

    In your cellForRow load the corresponding model object and set the accessoryType based on the property on your model class.

    Login or Signup to reply.
  2. You should implement both didSelectRowAt and didDeselectRowAt? On didSelect, turn on the checkmark. On didDeselect, turn it off.

    If you need the flags data, it is better to store it in a model (in your code, they are stored in the UI/cells), and keep the model & cells synchronised.

    Login or Signup to reply.
  3. Use tableView’s reloaddata(). I presume, this will fix the problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search