User User - 6 months ago 19
Swift Question

Tapping is required twice to uncheck table cell

When I load table view with checked cells and I want to uncheck a specific cell I need to tap twice on cell to uncheck it, I guess I know where's the problem but I don't how I can solve this issue?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("daySelected", forIndexPath: indexPath)
cell.selectionStyle = .None

cell.textLabel?.text = days[indexPath.row]

if indexPath.row == 0 && day[0] == true{
cell.accessoryType = .Checkmark
}


return cell
}
}


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

if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .Checkmark
}else{
cell!.accessoryType = .None
}
if indexPath.row == 0{
day[0] = true

}


}


override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
}

if indexPath.row == 0{
day[0] = false

}

}

Answer

You should only implement didSelectRowAtIndexPath, not didDeselectRowAtIndexPath. In there, to just flip the selection status, do

if let cell = tableView.cellForRowAtIndexPath(indexPath) {
      if cell.accessoryType == .Checkmark {
           cell!.accessoryType = .None
      }else{
          cell!.accessoryType = . Checkmark
      }
}
if indexPath.row == 0{
        //flip the day bit
        day[0] = !day[0]

    }
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)