I have a segmented controller with two segments. Each segment has one common tableView. How can I save selected cells when switching segments? Could you please give some idea how to achieve it?
I can save only one selected row when switching segments.
ViewModel
var years: [String] = []
var genres: [String] = []
var selectedGenr: Int?
var selectedYear: Int?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if segmentedControl.selectedSegmentIndex == 0 {
if viewModel.selectedGenr == indexPath.row {
viewModel.selectedGenr = nil
} else {
viewModel.selectedGenr = indexPath.row
}
} else {
if viewModel.selectedYear == indexPath.row {
viewModel.selectedYear = nil
} else {
viewModel.selectedYear = indexPath.row
}
}
tableView.reloadData()
}
}
CodePudding user response:
you can store selection as a list in the view model then in table view
pseudo-code
if segmentedControl.selectedSegmentIndex == 0 {
if viewModel.selectedYears.contains(indexPath.row) {
viewModel.selectedYears.remove(indexPath.row)
}
else {
viewModel.selectedYears.append(indexPath.row)
}
}
CodePudding user response:
if segmentedControl.selectedSegmentIndex == 0 {
if self.selectedIndexesForGenres.contains(indexPath.row) {
if let index = self.selectedIndexesForGenres.firstIndex(of: indexPath.row) {
self.selectedIndexesForGenres.remove(at: index)
}
} else {
self.selectedIndexesForGenres.append(indexPath.row)
}
}
else {
if self.selectedIndexesForYears.contains(indexPath.row) {
if let index = self.selectedIndexesForYears.firstIndex(of: indexPath.row) {
self.selectedIndexesForYears.remove(at: index)
}
} else {
self.selectedIndexesForYears.append(indexPath.row)
}
}
self.tableView.reloadData()
}