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.
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
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 clickedindexPath
.In your
cellForRow
load the corresponding model object and set theaccessoryType
based on the property on your model class.You should implement both
didSelectRowAt
anddidDeselectRowAt
? OndidSelect
, turn on the checkmark. OndidDeselect
, 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.
Use tableView’s reloaddata(). I presume, this will fix the problem.