PrLion PrLion - 1 year ago 84
iOS Question

How to choose and save multiple selections in a tableview

In Swift 3, how can I choose multiple selections in a tableview and save them? If I move back I want see what I selected before and change it! I am using

didSelectRowAtIndexPath
and
didDeselectRowAtIndexPath
.

When I open tableview and choose rows, all is OK. I can make my choices and go to the next ViewController. But when I move back to TableView I didn't see my selected rows and can't change my selection.

var selectedRows = Array<IndexPath>()

override func viewDidLoad() {
super.viewDidLoad()
subServicesTableView.allowsMultipleSelection = true
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SubServicesTableViewCell

cell.subServiceName.text = fetchedResultController.object(at: indexPath).name

if !selectedRows.isEmpty {
for row in selectedRows {
if row == indexPath {
cell.isSelected = true
cell.accessoryType = cell.isSelected ? .checkmark : .none
}
}
}

return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentCell = subServicesTableView.cellForRow(at: indexPath) as! SubServicesTableViewCell

currentCell.chooseMark.backgroundColor = UIColor.green
selectedSubServices.append(fetchedResultController.object(at: indexPath))
selectedRows.append(indexPath)
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let currentCell = subServicesTableView.cellForRow(at: indexPath) as! SubServicesTableViewCell
currentCell.chooseMark.backgroundColor = UIColor.clear
selectedSubServices = selectedSubServices.filter(){$0 != fetchedResultController.object(at: indexPath)}
selectedRows = selectedRows.filter(){$0 != indexPath}
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
for index in selectedRows {
if index == indexPath {

self.subServicesTableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
if let serviveCell = cell as? SubServicesTableViewCell {
serviveCell.chooseMark.backgroundColor = UIColor.green

}
}
}
}

Answer Source

Instead of recreating selectedRows every time your viewController is loaded, introduce a singleton where you can keep track of your selected IndexPath instances.

Here is simple implementation of a singleton class:

class RowsManager {
    static let shared = RowsManager()
    private init() {}
    var selectedRows = Array<IndexPath>()
}

From now on, instead of interacting with selectedRows, use RowsManager.shared.selectedRows.

Using a singleton is quick and fairly easy solution. However, there are many persistency techniques in the iOS echo system, like userdefaults, Core Data or writing to file system.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download