I have a UITableView
in one UIViewController
, and I try to store the status of the accessoryType so that when the user reload the app, the cells user selected beforehand using NSUserDefault
should display with a checkmark. But the problem I am facing is that when I check if the cell's data is equal to the data in the user default, some cells that weren't selected are displaying with a checkmark too, but it shouldn't do that.
here is my codes:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.backgroundColor = colorArray[indexPath.row]
let entry: Categories
if isFiltering() {
entry = filteredCategories[indexPath.row]
} else {
entry = categoryTitles[indexPath.row]
}
cell.selectionStyle = .none
cell.textLabel?.text = entry.name
cell.detailTextLabel?.text = entry.description
let defaults = UserDefaults.standard
if let userCategortList = defaults.object(forKey: "userCategoryList") as? [String]{
for category in userCategortList{
if(cell.textLabel?.text == category){
cell.accessoryType = .checkmark
break
}
}
}
return cell
}
This is likely a cell reuse issue since you're dequeuing cells. You need to make sure to set cell.accessoryType = .none
for the cases that aren't being set to the checkmark.
try with below snippet.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = newCategoriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.backgroundColor = colorArray[indexPath.row]
let entry: Categories
if isFiltering() {
entry = filteredCategories[indexPath.row]
} else {
entry = categoryTitles[indexPath.row]
}
cell.selectionStyle = .none
cell.textLabel?.text = entry.name
cell.detailTextLabel?.text = entry.description
let defaults = UserDefaults.standard
if let entry.name == (defaults.object(forKey: "userCategoryList") as? [String]){
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
return cell
}
Save entry.name in user defaults.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.