【问题标题】:UITableviewCell showing old data and new data on reloadUITableviewCell 在重新加载时显示旧数据和新数据
【发布时间】:2018-01-04 17:41:45
【问题描述】:

我有一个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:)

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

【问题讨论】:

  • 如果单元格被重复使用,您需要在再次使用之前清除其内容
  • 我添加了 let theSubviews: Array = (cell?.contentView.subviews)!在 theSubviews { view.removeFromSuperview() } 中查看,但子视图在 cellForRowIndexPath 中计数为 0
  • 请使用cellForRowIndexPath 代码更新您的问题。
  • @PhillipMills 添加。谢谢
  • 您正在将自定义视图添加为单元格的子视图,但是在您的评论中,您说您正在尝试将其从内容视图而不是单元格中删除。您可能希望将其添加到内容视图中。

标签: swift uitableview xib


【解决方案1】:

快速回答如下:由于单元格在出队时会被重复使用,因此您要向之前出队时已添加 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)

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

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2017-01-20
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多