Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting and Deselecting UITableViewCells - Swift

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.
like image 829
JohnJLilley Avatar asked Jan 08 '23 17:01

JohnJLilley


1 Answers

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()
}
like image 161
JohnJLilley Avatar answered Jan 22 '23 16:01

JohnJLilley