amirbt17
amirbt17

Reputation: 611

Selecting TableView Cell Activates Checkmark in Rows in Multiple Sections

I've implemented checkmarks (when row is selected) with the following code in cellForRowAt:

// Add a checkmark to row when selected
    if selectedIngredients.contains(indexPath.row) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }

However, when I select a row, that index.row from each section gets the checkmark: enter image description here

This seems like it could be because I'm only specifying the indexPath.row, but not the section. How can I code this so that only the selected row within the section I selected gets the checkmark?

Upvotes: 0

Views: 648

Answers (2)

hessam
hessam

Reputation: 432

use data store for save checkmarks like this:

var selectedIngredients: Set<IndexPath> = [] // use set for unique save

then didSelect callBack:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if self.selectedIngredients.contains(indexPath) {
            self.selectedIngredients.remove(indexPath)
            
        } else {
            self.selectedIngredients.insert(indexPath)
        }
        
        self.tableView.reloadData()
    }

after reload in CellForRow:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedIngredients.contains(indexPath) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
}

If you want it to have only one Row contain checkmark:

var selectedIngredients: IndexPath? = nil

and didSelect CallBack:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
            self.selectedIngredients = indexPath
        }

and finally:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if selectedIngredients == indexPath {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

Upvotes: 1

musakokcen
musakokcen

Reputation: 394

you should add checkmarks in didSelect and remove them in didDeselect methods;

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    // update cell here
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // update cell here
}

also, have a look at this answer; https://stackoverflow.com/a/34962963/13754736

Upvotes: 0

Related Questions