5

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.
JohnJLilley
  • 173
  • 1
  • 2
  • 10
  • In this code what are you trying to do? You get the currently tapped cell and then set the backgroundColor to purple. What is its purpose and is it working? – chrissukhram Mar 17 '15 at 01:26
  • Yes, I get the currently tapped cell and set the background to purple and it is working well. Now, I am trying to tap on that cell again and deselect it to the way it was before I selected it. – JohnJLilley Mar 17 '15 at 01:28

3 Answers3

8

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()
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
JohnJLilley
  • 173
  • 1
  • 2
  • 10
1

have you tried to create a simple bool and verify in the next tap. If its true you use the code bellow else you keep it tapped until you tap it again

tableView.deselectRow(at: indexPath, animated: true)

0

Updated Code Syntax for Swift 3 / 4

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let selectedCell = tableView.cellForRow(at: indexPath)
     currentCell.backgroundColor = UIColor.purple
 }

 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     let deselectedCell = tableView.cellForRow(at: indexPath)
     currentCell.backgroundColor = UIColor.clear
 }
Mithun Ravindran
  • 2,292
  • 2
  • 14
  • 23