Selecting and Deselecting UITableViewCells - Swift

JohnJLilley picture JohnJLilley · Mar 17, 2015 · Viewed 13.1k times · Source

Currently I am able to tap a cell and select it using didSelectRowAtIndexPath. However, I am unable to deselect it when tapped. I wish to toggle these two features.

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


    var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    selectedCell.backgroundColor = UIColor.purpleColor()

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

}
  • I have a TableView in my View Controller.
  • The dataSource and delegate are already set up.
  • Multiple selection is enabled in UIBuilder for the table.

Answer

JohnJLilley picture JohnJLilley · Mar 17, 2015

I could have sworn I tried this before and it didn't work then.

I decided to use two functions..

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    selectedCell.backgroundColor = UIColor.purpleColor()        
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    var deselectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    deselectedCell.backgroundColor = UIColor.clearColor()
}