Igor Tupitsyn Igor Tupitsyn - 6 months ago 29
Swift Question

UITableView: highlight the last cell but other cells get highlighted as well

I have UITableView that I use as a sliding menu as part of SWRevealViewController.

I want to select the last cell in UITableView and implement the following:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! IGAWindAloftMenuTableViewCell

...


let sectionsAmount = tableView.numberOfSections
let rowsAmount = tableView.numberOfRowsInSection(indexPath.section)

if (indexPath.section == sectionsAmount - 1 && indexPath.row == rowsAmount - 1)
{
customCell.backgroundColor = UIColor.yellowColor()
}

return customCell
}


When I scroll all the way down, it works -- the last cell is highlighted. However, when I scroll up and down, other cells in the middle of the table get highlighted as well.

Is there any way to prevent it?

Thank you!

Answer

You have to undo the change made in the if-branch for all other cells:

if (indexPath.section == sectionsAmount - 1 && indexPath.row == rowsAmount - 1) {
    customCell.backgroundColor = UIColor.yellowColor()
} else {
    customCell.backgroundColor = UIColor.whiteColor() // or whatever color
}

The reason for the undesired side effect is the reusing of cells. A cell gets created, then it gets used as the last cell, then it moves off-screen and is reused somewhere else. It still contains the changed color information but is no longer at the corresponding position.