Search code examples
uitableviewswift3

Interact with cell


I want to change background and on text color of cell on tap, and keep active status this for cell until other cell is taped. This active status will lose. I use Swift 3 and this is my source :

let selectedView = UIView()
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
   let cell  = tableView.cellForRow(at: indexPath)
   selectedView.backgroundColor = UIColor.red
   cell!.selectedBackgroundView = selectedView
   cell!.textLabel?.textColor = UIColor.white

   return true
}

This code worked but it not remove active status


Solution

  • 1st: Is there any reason you use a separate view instead of just using cell?.backgroundColor?

    2nd: You shouldn't use force unwrap. Either use ? or use optional binding

    3rd: You probably should rather use tableView(_:didSelectRowAt:) for this, since tableView(_:shouldHighlightRowAt:) is more for the system hilight.

    4th: To solve your problem, you should keep a pointer around to the cell that you currently hilight. So when you call tableView(_:didSelectRowAt:) again first think you can do is reset the old cell's hilight.