首页 > 解决方案 > 更改表格第一个单元格的背景图像

问题描述

我使用表格视图创建了一个记分板,我想突出显示表格的第一行。当我运行应用程序时,第一行按预期突出显示,但是当我滚动表格时,突出显示了几个单元格而不是第一个单元格。

这是我的代码;

    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
}

标签: iosarraysswiftxcodeuitableview

解决方案


单元格出列意味着当您cellForRow被要求输入单元格(这不是第一个)时,返回的单元格可能会使第一个单元格出列,因此请确保nil通过替换来设置它不是索引为零的时间

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

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

推荐阅读