重复使用自定义 tableView 单元格时重复显示相同的子视图 (Swift 4.1)

Same subview shows repeatedly when custom tableView cell reused (Swift 4.1)

我在自定义 tableView 单元格中绘制一组 CGRects 时遇到问题,当单元格被重复使用时它们会重复显示,这不是我想要的。

这是我的 tableView 控制器中的 tableView(cellForRowAt indexPath:) 函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! CustomTableViewCell

    cell.addBlock(item: itemArray[indexPath.row])

    cell.itemTitle.text = itemArray[indexPath.row].itemTitle

    return cell
}

这是我的 CustomTableViewCell class 中的函数:(使用 xib 文件创建)

func addBlock(item: Item) {
    for i in 0 ..< item.numberOfBlocks {
        let block = UIView()
        block.frame = CGRect(
            origin: CGPoint(
                x: CGFloat(i) * 10,
                y: 0
            ),
            size: CGSize(
                width: 10,
                height: bounds.size.height
            )
        )
        block.backgroundColor = UIColor.orange
        self.addSubview(block)
    }
}

我想我根据 itemArray 项目中的 numberOfBlock 属性 绘制每个单元格,但是当单元格被重复使用时,块不会重绘... 我尝试在这里和其他地方搜索,但我找不到答案(很长时间),我是新手 swift,请耐心等待...非常感谢。

注意: 项目 class 包含 2 个属性: 1. itemTitle:字符串, 2. numberOfBlocks: Int

我相信您遇到了这个问题,因为 let block = UIView() 没有在重用时从单元格中删除。如果是,你可以试试这个策略:

  1. 把握住你的每一个let block = UIView() CustomTableViewCell class;
  2. 实施 prepareForReuse() 方法并从超级视图中删除所有 block

此步骤保证重复使用的单元格没有来自先前状态的任何块。

一些实现:

final class CustomTableViewCell: UITableViewCell {

    private var blocks: [UIView] = []

    override func prepareForReuse() {
        super.prepareForReuse()

        blocks.forEach { [=10=].removeFromSuperview() }
        blocks = []
    }

    func addBlock(item: Item) {
        for ... {
            let block = UIView()
            ...
            blocks.append(block)
        }
    }

}