sunny
sunny

Reputation: 61

TableView cell selection issue

So I selected a cell in tableview. it expands, shows detail text of the that cell then I started scrolling down till this selected cell goes out of view. because of reuse identifier other cell in the the view get some the property of the selected cell automatically.

Is there any way to handle this ?

var selectedIndex = -1

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UIView.animate(withDuration: 1) {
        self.labelViewHeightConstraint.constant = 60
        self.labelLeadingConstraint.constant = 136
        self.view.layoutIfNeeded()
    }


    let cell = tableView.cellForRow(at: indexPath) as! CustomCell
    if(selectedIndex == indexPath.row) {
        selectedIndex = -1
            print("deselect")
        UIView.animate(withDuration: 0.4) {

            cell.secondView.isHidden = true
            cell.firstView.backgroundColor =  UIColor(red: 0.8588, green: 0.84705, blue: 0.8745, alpha: 1.0)
        }
    } else {
        cell.secondView.isHidden = false
    }
        self.expandTableView.beginUpdates()
        //self.expandTableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic )
        self.expandTableView.endUpdates()
    }

And i have deselect tableview function as

   func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPathaddres  , animated: true)
        if let cell = tableView.cellForRow(at: indexPath) as? customCell {
            cell.firstView.backgroundColor =  UIColor(red: 0.8588, green: 0.84705, blue: 0.8745, alpha: 1.0)
            print("deselected row")
        }
    }

I have already disabled multiple selection.

I am attaching the 2 screenshot. I 1 is select first cell of tableview then scroll down https://drive.google.com/file/d/1RZlya_eVVjDzj02GKV9h0qJU8F29xMin/view?usp=drivesdk once that cell goes out of scope. Jump server 3 (as seen in this screenshot gets selected) https://drive.google.com/file/d/15k4gLUPkgB6jGZ7AWR6km0Jajst9KKxM/view?usp=drivesdk get selected

Upvotes: 0

Views: 372

Answers (1)

HAK
HAK

Reputation: 2081

Since tableview reuses its cells, you need to do some extra checks if you want your one cell to be different from the others.

  1. Reset the cell to its default in prepareForReuse method. Like hiding your view and reset the arrow direction in your case.
  2. Check for selected index in your cellForRow method and expand your view like you do in your didSelectRow method and hide it if its not selected just as you do in your didDeselect method.

Upvotes: 2

Related Questions