Home > OS >  changing the background image of first cell of the table
changing the background image of first cell of the table

Time:09-17

I created a score board using table view and I want to highlight the first row of the table. When I run the app, the first row is highlighted as expected but when I scroll the table, several cell is highlighted instead of first cell.

Here is my code;

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "score", for: indexPath) as! ScoreTableViewCell
    if indexPath.row == 0 {
        cell.backgroundImageView.image = UIImage(named: "firstClass")
    }
    cell.nicknameLabel.text = self.sortedResults[indexPath.row]["nickname"] as? String
    cell.scoreLabel.text = " \(indexPath.row   1)"
        
    return cell
}

CodePudding user response:

Cells are dequeued meaning when your cellForRow is asked for cell ( that's not the first one ) the returned cell may dequeue that first cell so make sure to set nil when it's not index zero by replacing

if indexPath.row == 0 {
    cell.backgroundImageView.image = UIImage(named: "firstClass")
}

with

cell.backgroundImageView.image = indexPath.row == 0 ?  UIImage(named: "firstClass") : nil 
  • Related