3

I have a tableview with a custom cell. Below image shows the view hierarchy of my tableview cell.

enter image description here

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?

udi
  • 303
  • 1
  • 6
  • 19

3 Answers3

4

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)
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
3

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!

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
  • 2
    your solution also working. Unfortunately I can accept only one answer. But thanks for your support. – udi Nov 01 '17 at 05:33
-1

first be sure your

 tableview.delegate = self

second thing in did select row at index use that code

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! AccountsTableViewCell


    cell.checkImage.isHidden = false
}