0

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
}
Rishi Chaurasia
  • 520
  • 4
  • 18
Martin.Zeng
  • 63
  • 1
  • 4

2 Answers2

0

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.

raidfive
  • 6,603
  • 1
  • 35
  • 32
  • 1
    Might be good to mention that this would be often done in a `prepareForReuse` method on the custom cell (if one exists) – JMFR Nov 07 '17 at 23:32
0

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.

Rishi Chaurasia
  • 520
  • 4
  • 18