首页 > 解决方案 > 滚动时显示重复数据的 CollectionView 单元格?

问题描述

我在表格视图中创建了用于滚动二维(水平 - 垂直)的集合视图并且我从 JSON API 获取数据在第一次尝试时一切正常但是当我向下滚动时出现问题:

收集视图获取重复数据。它在单元格中显示错误的图像和文本数据。

我该如何解决这种情况?代码如下。

这是我的主要 TableView 的 cellForRowAt:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: exploreCellIDColl, for: indexPath) as! TableExploreCell

    cell.postCategory = exploreCategories?[indexPath.row]

    return cell
}

这个是 TableViewCell 中的 CollectionView cellForItemAt:

// I created collection view in tableview cell
let cellCollectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let collView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collView.backgroundColor = .clear
    return collView
}()

 // This part showing duplicated wrong data (image and text)

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: exploreCellID, for: indexPath) as! CollectionExploreCell

           cell.postsExplore = postCategory?.post?[indexPath.row]
            self.postCategory?.post?.append(contentsOf: model.data ?? [])
            self.cellCollectionView.reloadData()

    return cell
}

标签: swiftuitableviewuicollectionviewduplicates

解决方案


这是每个人第一次开始使用集合视图和表视图时都会遇到的常见问题。问题是细胞被回收了。当您在滚动后调用 dequeueReusableCell 时,您可能会传递一个刚刚滚动到屏幕外并且在其视图中包含上次使用的内容的单元格。无论模型数据如何,您都必须让您的 cellForItemAt/cellForRowAt 代码始终为每个字段设置一个值。

cellForItemAt()如果您的模型的各个部分不为零(问号和下面的行),您的代码使用可选链接来设置单元格视图postCategory?.post?[indexPath.row]。您需要改为使用if let或其他方法,始终将每个字段设置为一个值,并在数据模型的相应部分为 nil 时将其设置为空值。

另请注意,您永远不应该调用reloadData()inside cellForItemAt。这将导致一个无限循环,其中集合视图尝试返回一个单元格,然后将所有单元格扔掉并开始加载新的单元格,但每次它返回一个新单元格时,都会再次将它们全部扔掉。


推荐阅读