Home > OS >  Maintain collection view selected state after table view cell reloadData
Maintain collection view selected state after table view cell reloadData

Time:09-17

I have a collection view and some other data as part of a table view cell. The collection view cells are selectable ensuring a single selection of an item. The use case now is I need to make an API call that will refresh the cell's data. After the API is fetched, I reload the table view cell with:

tableView.reloadRows(at: [indexPath], with: .automatic)

The issue is reloading the table view also loses the collection view cell selected state. Is there any way to preserve the selected state or reload the cell without reloading the collection view?

Anyone has ideas, please help.

CodePudding user response:

The simplest option I can think of is to use UICollectionView with compositionalLayout instead of your tableView and save the selected item index.

Another option is to save the selected state of the collectionView objects in your tableView dataSource, i.e. let's say you have a list of items (of type A) building your tableView cells, one of them has a list of items (of type B) building the collectionView cells, when you select an item (of type B), update that item in the outer list (of items of type A)

When fetching new results, make sure to update the selected state from the current results before replacing.

CodePudding user response:

My idea is to use one variable. And every time you click cell, you update indexPath to the variable.

var clickCell: IndexPath?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  clickCell = indexPath // update value
}

and after reloading the table view add this code

if let index = clickCell {
  tableView.selectRow(at: index, animated: true, scrollPosition: .none)
}

  • Related