I have a tableview with a custom cell. Below image shows the view hierarchy of my tableview cell.
When adding rows to the tableview I'm hiding the 'check Image' imageview using below code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = true
return cell
}
and when a row is clicked I'm showing the imageview again. Below is the code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = false
}
But the problem is when I click a row nothing happens. system execute the cell.checkImage.isHidden = false
code line, but the imageview doesn't appear. It is still hidden. Could someone tell me what I'm doing wrong here?
You can't track cell checked status in your cell itself; the cell object is just a view onto your data and cells will be reused when the table view scrolls.
I suggest using a Set<IndexPath>
. In your cellForRowAt
you can check the contents of the set in order to determine whether the checkmark should be hidden:
var checked = Set<IndexPath>()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = self.checked.contains(indexPath)
return cell
}
in your didSelectRowAt
you simply toggle the set membership and reload the row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.checked.contains(indexPath) {
self.checked.remove(indexPath)
} else {
self.checked.insert(indexPath)
}
tableView.reloadRows(at:[indexPath], with:.fade)
}
You have to manage your array (datasource)! when you click your row, update your array for that index and reload your table view.
Example :
Your array should have some flag like isChecked
toggle it's value from true to false or vice-versa.
In your cellForRowAtIndexPath
check this flag and show or hide your image according to that flag!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With