Ctibor Šebák
Ctibor Šebák

Reputation: 133

Make UITableViewCell flash briefly

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!

Upvotes: 1

Views: 1306

Answers (2)

EmilioPelaez
EmilioPelaez

Reputation: 19912

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
}

Upvotes: 4

Ctibor Šebák
Ctibor Šebák

Reputation: 133

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.

Upvotes: 0

Related Questions