2

I can not understand why I can not toggle a selected table row. I am successfully setting the accessoryType in didSelectRowAt. But I can not seem to set the accessoryType to none in didDeselectRowAt.

enter image description here

my data:

serviceItems = ["Heater", "Air Conditioner", "Boiler", "Heat Pump"]

here are my tableview overrides:

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.accessoryType = .checkmark
    let serviceItem = serviceItems[indexPath.row] as! String
    cell.textLabel?.text = serviceItem
}

// does not remove checkmark
// does not change textLabel to "test" 
// DOES print "DESELECTING" (so I know its getting called)
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.accessoryType = .none
    cell.textLabel?.text = "test"
    print("DESELECTING")
}
Sam Luther
  • 1,170
  • 3
  • 18
  • 38
  • 1
    Possible duplicate of [UItableviewcell Checkmark to be toggled on and off when tapped SWIFT](http://stackoverflow.com/questions/30059704/uitableviewcell-checkmark-to-be-toggled-on-and-off-when-tapped-swift) – 0ndre_ Nov 30 '16 at 22:08
  • @theMikeSwan u had the answer if you wanna post it – Sam Luther Nov 30 '16 at 22:33

2 Answers2

6

Should have been using tableView.cellForRow instead of tableView.dequeueReusableCell

Changed:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

To:

let cell = tableView.cellForRow(at: indexPath)
Sam Luther
  • 1,170
  • 3
  • 18
  • 38
1

I put everything in the DidSelectRow see here :

func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
{
    if let cell = tableView.cellForRow(at: indexPath) {
        if self.selectedIndexPaths.contains(indexPath)
        {
            // Config Cell
            cell.accessoryType = .none
            self.selectedIndexPaths.remove(indexPath)
        }
        else
        {
            // Config Cell
            cell.accessoryType = .checkmark                    
            self.selectedIndexPaths.add(indexPath)
        }
        // anything else you wanna do every time a cell is tapped
    }    
}
Jp4Real
  • 1,982
  • 4
  • 18
  • 33