我有一个UITableViewCell
,我在xib
方法中添加cellForRowIndexPath
。它工作正常,直到我更新模型并在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
对我来说,这感觉有点矫枉过正,因为看起来你应该将你的customView添加到一个自定义的qazxswpoi,所以你实际上并不是在动态创建一个自定义单元格,但这只是我。如果您这样做,您可以简单地将自定义单元格出列并在标签上设置文本,而无需始终向层次结构添加更多视图。