fs_tigre
fs_tigre

Reputation: 10738

Checkmark changes after scrolling in table view

No matter what I do I cannot keep the checkmark item selected after scrolling. I know this has to do with the fact that the cells are reused when items are visible but I'm not sure how to handle this.

The following code successfully shows the right item selected on the first load, the issue is that once I start scrolling it randomly keeps selecting other items.

What is the proper way to keep the selected item after scrolling and prevent from selecting unwanted items/rows?

class CategoriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    var categories: Results<Category>! // I'm getting this from the Realm data base 
    var categoryTracker:Category? // I'm getting this from other view controler
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "categoriesCell", for: indexPath) as! CategoriesCell
        
        let categoryList = categories[indexPath.row]
        cell.labelCategoryName.text = categoryList.categoryName

        if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID{
            cell.accessoryType = .checkmark
        }
        
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        // show checkmark on category for selected item and uncheck the rest
        for row in 0..<tableView.numberOfRows(inSection: indexPath.section) {
            if let cell = tableView.cellForRow(at: IndexPath(row: row, section: indexPath.section)) {
                cell.accessoryType = row == indexPath.row ? .checkmark : .none
            }
        }
    }
}

Images:

enter image description here

Upvotes: 1

Views: 94

Answers (1)

Daniel E. Salinas
Daniel E. Salinas

Reputation: 441

You are right. This happens because when a cell with .checkmark is reused, it is not reseting its accessory type back to .none

You should update your:

if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID{
    cell.accessoryType = .checkmark
}

to:

if categories[indexPath.row].categoryID == self.categoryTracker!.categoryID {
    cell.accessoryType = .checkmark
} else {
    cell.accessoryType = .none
}

Upvotes: 2

Related Questions