0

I'm facing the same issue as asked in this question:

how can i store selected rows of tableview in nsuserdefaults in swift 3

However, I'm interested in knowing how to repopulate with the saved rows that have been checkmarked?

Thank you!

javadoe
  • 9
  • 2

1 Answers1

2

Create a variable with didSet so that we can reload table once the value is assigned to it.

var selectedRows: [Int] = [] {
    didSet {
        myTableView.reloadData()
    }
}

On viewDidLoad() assign value to selectedRows from userDefaults

override func viewDidLoad() {
    super.viewDidLoad()        
    selectedRows = UserDefaults.standard.value(forKey: "selectedRows") as? [Int] ?? []
}

Use this code to update cell.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "myCell")
    cell.textLabel?.text = "\(indexPath.row)"
    cell.accessoryType = selectedRows.contains(indexPath.row) ? .checkmark : .none
    
    return cell
}

Finally in didSelectRowAt use this logic to update selectedRows variable and store it to userDefaults.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedRows.contains(indexPath.row) {
        self.selectedRows = selectedRows.filter{$0 != indexPath.row}
    }else{
        self.selectedRows.append(indexPath.row)
    }
    UserDefaults.standard.set(selectedRows, forKey: "selectedRows")
}

If you want to store selected index in userdefault on button click, you can use following example.

//
// Within SMViewController.swift file.
//
class SMViewController: UIViewController, UITableViewDataSource {
    
    @IBOutlet weak var myTableView: UITableView!
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: SMCell = tableView.smDequeueReusableCell(forIndexPath: indexPath)
        cell.delegate = self
        return cell
    }
    
}

extension SMViewController: MyCellDelegate {
    func didClickButton(cell: SMCell) {
        if let indexPath = self.myTableView.indexPath(for: cell) {
            // 1) Get all indexes
            var allIndexes = UserDefaults.standard.array(forKey: "myIndexes") as? [Int] ?? []
            // 2) Append current selected index
            allIndexes.append(indexPath.row)
            // 3) Store updated indexes in user defaults.
            UserDefaults.standard.setValue(allIndexes, forKey: "myIndexes")
        }
    }
}

//
// Within SMCell.swift file.
//
protocol MyCellDelegate: AnyObject {
    func didClickButton(cell: SMCell)
}

class SMCell: UITableViewCell {
    weak var delegate: MyCellDelegate?
    @IBOutlet weak var myButton: UIButton!
    
    /// Link this button to your `TableViewCell`
    @IBAction func smButtonHandler(_ sender: UIButton) {
        self.delegate?.didClickButton(cell: self)
    }
}

I hope this is helpful. Let me know if you do have any confusion.

Thanks

Santosh
  • 363
  • 2
  • 14
  • Great. It would be much better if you can upvote and mark as answered. – Santosh Oct 19 '18 at 10:05
  • @DilipTiwari can you explain more? Where you want to show image? And with above cost, you will get cell selected which was selected last time. If you mean different about selection, let me know. – Santosh May 01 '19 at 10:05
  • @DilipTiwari, this solution is for you. http://santoshm.com.np/2019/05/01/store-selected-cell-in-tableview/ – Santosh May 01 '19 at 11:00
  • Hi, thank you for the answer! Your solution works perfect :) Could u please say how to save selected rows with button action? I tried to save indexes with UserDefaults in button func, but it not showing selected rows. – Abrcd18 Aug 29 '21 at 12:22
  • 1
    Hello @Abrcd18, here is a solution for you. https://santoshm.com.np/2019/05/01/store-selected-cell-in-tableview/#abrcd18 – Santosh Aug 30 '21 at 13:21
  • 1
    Hi @Abrcd18, I have updated the answer as well. Hope this helps. – Santosh Aug 31 '21 at 05:38
  • Thank you very much! I forgot to say that my button "save" is placed in the bottom of view not inside tableView. I will try your code. Logic must be the same. – Abrcd18 Aug 31 '21 at 08:36
  • Solved the task. I forgot to call UserDefaults.standard.synchronize() – Abrcd18 Aug 31 '21 at 10:00