【问题标题】:changing the background image of first cell of the table更改表格第一个单元格的背景图像
【发布时间】:2021-11-05 07:12:03
【问题描述】:

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

这是我的代码;

    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
}

【问题讨论】:

  • 使用 2 个不同的单元原型。一个用于第 0 行,带有 backgrounImagzView,另一个不带。

标签: ios arrays swift xcode uitableview


【解决方案1】:

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

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

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

【讨论】:

  • 当我用你的建议替换我的代码时,只有第一个出现,其他的没有显示在 tableview 中
  • 而不是 nil 设置 UIImage(named: "otherClass") 如果您有超过 2 行保留图像数组或在 cellForRow 内设置一个开关盒 indexPath.row 以根据当前索引设置适当的图像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 2013-06-15
  • 2014-01-23
相关资源
最近更新 更多