how can i save checked rows of tableview in userdefault?

♀尐吖头ヾ 提交于 2021-02-08 10:26:02

问题


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!


回答1:


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")
}

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

Thanks



来源:https://stackoverflow.com/questions/51911991/how-can-i-save-checked-rows-of-tableview-in-userdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!