1

I have a UITableView set-up and I am exploring all the different options of highlighting the UITableViewCell and I was wondering the following:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        .
        .
    cell.selectionStyle = .gray
    return cell
}

What happens now is that when a cell is selected it is highlighted with a grey color, I was wondering, is it possible to deselect the cell after about 0.5 sec?

Basically is it possible to make the cell only flash briefly so the user knows he interacted with the cell, however it does not stay selected? I am using this tableView for a side menu and staying highlighted is not the desired behavior for me.

Thanks!

Ctibor Šebák
  • 133
  • 1
  • 14

2 Answers2

4

You could deselect the row on the didSelectRow method, the cell will be highlighted and then the selection will fade out, letting the user know that they interacted with the cell.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  tableView.deselectRow(at: indexPath, animated: true)
  // Do whatever else you need
}
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50
0

Finally got it to work, what I did was:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 tableView.cellForRow(at: indexPath)?.backgroundColor = .gray
    DispatchQueue.main.asyncAfter(deadline: .now()) {
        UIView.animate(withDuration: 0.5, animations: {
            tableView.cellForRow(at: indexPath)?.backgroundColor = .none
        })
    }

Maybe this will help someone else. The only problem is, that the tapped cell does not highlight when pressed, only after the gesture has ended (i.e. only tapped). If anybody has solution for this I would appreciate it, but for now this will do.

Ctibor Šebák
  • 133
  • 1
  • 14
  • 1
    First of all, I guess `DispatchQueue.main.asyncAfter(deadline: .now())` is not necessary. UIView.animate should run on main thread. Anyways, Emilios answer is probably more correct as it deselects cell, yours only changes the background. – Luzo Oct 30 '18 at 18:49
  • It works for me this way because I am only using the tableView for a side menu, but I understand that from a clean code perspective and for the future it is better to deselect the row if I don't need the cell to be selected. Thanks! – Ctibor Šebák Oct 30 '18 at 19:01