Search code examples
swifttableview

unselect cell in tableview if the cell is visible


In a tableview, the multiple selection is set in the storyboard. The following code is used to unselect a cell:

tableView.deselectRow(at: indexPath, animated: true)

It works fine if the cell is not visible. If the cell is visible, the selection check mark is gone. However, the cell seems still to be in selection mode, and it cannot be selected again.

Here is more information for my case: I have a tabview with 2 tabs. One is for editing data, and the other is for displaying data in a tableview.

In the second tabview, I made selections of cells. Then switch to the first tabview of the data source. If there is any change in the data source, I'll set a flag about the change.

In the second tabview, I'll clear any selection if the flag is on.

override open func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  if isDatasourceChanged {
    let selRows =
        tableView.indexPathsForVisibleRows ?? []
        for ip in selRows
        {
            tableView.deselectRow(at: ip, animated: true)
        }
    }
}

For example, here is the cell is selected:

enter image description here

I changed the datasource first, and then back to the second tabview. The viewWillAppear event is called and all selections are set to deselected. The visible cell looks like this: the selection check mark is gone, but it looks like it is still highlighted and cannot be selected again.

enter image description here

How can I set the cell unselected and not hilighed if it is visible?


Solution

  • After several days investigation and tries, finally I found a solution. The solution is actually very simple: just clear all the selections of the visible cells in tableView in the event of viewWillDisappear!

    override func viewWillDisappear(_ animated: Bool)
    {
      super.viewWillDisappear(animated)
      guard let ips = tableViewInBase.indexPathsForSelectedRows
        else { return }
      // deselect all select rows in tableview on exit
      // this will guaranty selection works again on
      // appearance!
      for ip in ips {
        selectRow(select: false,
          tableView: tableViewInBase,
          at: ip)
        }
      }
      ...
    }
    

    I wrote a blog with detail information at Unselect cell in tableview if the cell is visible