Selecting and Deselecting UITableViewCells - Swift
13,782
Solution 1
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()
}
Solution 2
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)
Author by
JohnJLilley
Updated on June 07, 2022Comments
-
JohnJLilley about 2 years
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 myView Controller
. - The
dataSource
anddelegate
are already set up. - Multiple selection is enabled in
UIBuilder
for the table.
- I have a
-
Felipe over 8 yearsBloody hell, mate! Thanks a million. Cheers.