当自定义表视图单元格重用时,同一子视图会重复显示 (Swift 4.1)



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

这是 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类中的函数:(使用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 Items 中的 numberOfBlock 属性绘制每个单元格,但是当单元格被重用时,块不会重新绘制......我尝试过在这里和其他地方搜索,但我找不到答案(很长一段时间(,我是 swift 的新手,请耐心等待......谢谢。

注意:项目类包括 2 个属性:1. 项目标题:字符串,2. 区块数:国际

我相信

您有这个问题,因为重用时let block = UIView()不会从单元格中删除。如果是,您可以尝试以下策略:

  1. 把你CustomTableViewCell班上的每一个let block = UIView()都拿下来;
  2. 实现prepareForReuse()方法并从超级视图中删除所有block

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

一些实现:

final class CustomTableViewCell: UITableViewCell {
    private var blocks: [UIView] = []
    override func prepareForReuse() {
        super.prepareForReuse()
        blocks.forEach { $0.removeFromSuperview() }
        blocks = []
    }
    func addBlock(item: Item) {
        for ... {
            let block = UIView()
            ...
            blocks.append(block)
        }
    }
}

最新更新