UITableviewCell 在重新加载时显示旧数据和新数据

UITableviewCell showing old data and new data on reload

我有一个 UITableViewCell,我正在 cellForRowIndexPath 方法中添加 xib。它工作正常,直到我更新模型并在 UITableView 上调用 reloadData。该单元格在旧数据之上显示新数据,我可以看到旧标签文本上的标签。

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

 let customView:CustomView = UIView.fromNib()
            userView.frame = CGRect(x: 10, y: y, width: Int(self.tableView.bounds.size.width-50), height: 50)
userView.label.text = data[indexPath.row]
cell.addSubview(customView:)

猜猜为什么会发生这种情况?

快速回答是这样的:由于单元格在出列时会被重复使用,因此您要将新的 CustomView 添加到先前在出列时已添加 CustomView 的单元格。

处理此问题的一种方法是从层次结构中删除任何现有的 CustomView,然后再创建并添加新的层次结构。为此,您可以每次都向视图添加一个可识别的标签,然后在您的出队过程中查找具有相同标签的视图以将其删除,如下所示:

//Remove existing view, if it exists
if let existingView = cell.viewWithTag(999) {
  //A view was found - so remove it.
  existingView.removeFromSuperview()
}
let customView: CustomView = UIView.fromNib()

//Set a tag so it can be removed in the future
customView.tag = 999
customView.frame = CGRect(x: 10, y: y, width: Int(self.tableView.bounds.size.width-50), height: 50)
customView.label.text = data[indexPath.row]
cell.addSubview(customView)

对我来说,这感觉有点矫枉过正,因为您似乎应该将自定义视图添加到自定义 UICollectionViewCell 中,这样您实际上并不是在动态创建自定义单元格,但我就是这样。如果这样做,您可以简单地使自定义单元格出列并设置标签上的文本,而不必一直向层次结构添加更多视图。