【发布时间】:2020-04-08 13:14:40
【问题描述】:
我在表格视图中创建了用于滚动二维(水平 - 垂直)的集合视图 我从 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
}
【问题讨论】:
-
当 UICollectionView 滚动时,滚动到屏幕外的单元格被重用。但是这些单元格在重用之前不会被清除,因此它们可以包含以前使用的数据/图像。在
cellForRowAt确保更新单元格的所有值/属性。你在哪里设置单元格的图像?
标签: swift uitableview uicollectionview duplicates