问题
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