Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ios show/hide views inside a tableview cell

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?

like image 809
udi Avatar asked Sep 12 '25 22:09

udi


2 Answers

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)
}
like image 193
Paulw11 Avatar answered Sep 14 '25 13:09

Paulw11


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!

like image 30
Ketan Parmar Avatar answered Sep 14 '25 12:09

Ketan Parmar