I have a tableview with 3 cells, I need to update my tableview, at the moment I am using reloadData, but I would like to save the cell selection when the tableview is closed and then reopened, I would also like to save the style of that cell, that is the background color, the label color.
This is my code:
extension UITableView {
func reloadDataSavingSelections() {
let selectedRows = indexPathsForSelectedRows
reloadData()
if let selectedRow = selectedRows {
for indexPath in selectedRow {
selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
}
class MainViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
_view.tableView.reloadDataSavingSelections()
}
}
2
Answers
You need to store the selected values because
indexPathsForSelectedRows
will be cleaned afterreloadData()
. You can use aSet
to store selected index paths, for example:I believe you can implement
tableView(_:willDisplay:forRowAt:)
method ofUITableViewDelegate
to set selection:Assuming you have a data source with unique identifiers, you can store and match against underlying data model rather than index paths to determine the selected cell.