Frodgers Frodgers - 9 months ago 31
Swift Question

UITableViewCell Checkmark Being Added to multiple rows when one is tapped

I have a tableview where not all of the cells are visible at once. I am trying to make it so that when a row is tapped it adds a checkmark accessory to the cell. My issue is that it adds it to other rows as well. In my table view there are 4 rows fully showing and a fifth one barely showing. If I check the first box it will then add a check mark to every fifth box (e.g. indexPath.row = 0,5,10,15...) despite the indexPath.row being different.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell: DropDownMenuCell = tableView.dequeueReusableCellWithIdentifier("DropDownMenuCell", forIndexPath: indexPath) as! DropDownMenuCell
cell.dropDownCellLabel?.text = DropDownItems[indexPath.row].Name
return cell

}


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let selectedCell: DropDownMenuCell = tableView.cellForRowAtIndexPath(indexPath) as! DropDownMenuCell
print(indexPath.row)
if selectedCell.accessoryType == .None {
selectedCell.accessoryType = .Checkmark
} else {
selectedCell.accessoryType = .None
}

}


Edit: Apologies for the duplicate, my initial search for this question didn't show the other question. I got a working answer here in swift already or I would try and go through the objective c post to solve my problem.

Answer Source

Maintain in your Data source which cell is to be selected.

Then in cellForRowAtIndexPath:

if (DropDownItems[indexPath.row].isSelected) {
    cell.accessoryType = .Checkmark
} else {
    cell.accessoryType = .None
}

and in your didSelectRowAtIndexPath Method:

if(DropDownItems[indexPath.row].isSelected) {
    DropDownItems[indexPath.row].isSelected = false
} else {
    DropDownItems[indexPath.row].isSelected = true
}

self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)