【问题标题】:Same subview shows repeatedly when custom tableView cell reused (Swift 4.1)重用自定义 tableView 单元格时重复显示相同的子视图(Swift 4.1)
【发布时间】:2018-03-20 17:45:31
【问题描述】:

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

这是我的 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 类中的函数:(使用 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 新手,请多多包涵……非常感谢。

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

【问题讨论】:

  • 看起来你正在添加子视图每次你出列一个单元格。您需要重新使用它们,或者在添加新的之前删除它们。

标签: ios swift uitableview subview


【解决方案1】:

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

  1. 在你CustomTableViewCell类中保持每个let block = UIView()
  2. 实现prepareForReuse()方法并从superview中删除所有blocks。

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

一点实现:

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)
        }
    }

}

【讨论】:

  • 非常感谢!我只是在 5 分钟前弄清楚...,我通过将我的 CGRects 转换为一个新类来删除了 cellForRowAt 函数中的块,并删除了该类中的所有 subView ......但是你用我没有的新方法启发了我没想到,谢谢
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多