4thSpace 4thSpace - 3 months ago 6x
iOS Question

How to un-highlight tableview cell?

I'm using


aCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? UITableViewCell

where aCell is a class level variable.

This works fine but I noticed clicked cells remain gray. Is there a way to un-highlight them when another cell is clicked?

I can store the previously clicked NSIndexPath but I'm not sure how to access any type of cell un-highlight method or property.


1. How to Get a Reference to a Visible Cell

It's not entirely clear from your question but it looks like you're using dequeueReusableCell(withIdentifier:forIndexPath:) inside tableView(_:didDeselectRowAtIndexPath:).

You shouldn't do that.

dequeueReusableCell(withIdentifier:forIndexPath:) is intended to be used inside tableView(_:cellForRowAtIndexPath:) where you configure your cells. It either creates and initializes a new cell or returns a cell for reuse that was scrolled off screen. The point is: It will never return a pointer to cell that's currently visible.

If you want to get a reference to a currently visible cell use cellForRowAtIndexPath(_:) instead on the table view.

2. Properly Deselecting a Cell

If you only want to deselect a cell at a certain index path you don't even need to get a reference to the actual cell. You can simply achieve the desired behavior by passing the indexPath of the row to the table view's deselect method. For example, if you want to animatedly deselect a cell right after the user has tapped on it, you can do it like this:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

3. More Information

For further information please refer to the Table View Programming Guide for iOS and the documentation of the method dequeueReusableCell(withIdentifier:forIndexPath:) in the UITableView Class Reference.