ios - UITableView 内的 Collection View 重用问题

标签 ios swift uitableview uicollectionview

我有一个 TableView,里面有一个 CollectionView。 因此每个 Table 单元格都是 CollectionView 的委托(delegate)。

问题在于 Collection View 在主线程上重新加载,并且 UITableView 单元格被重用。 这会导致 collectionView 单元格短暂显示先前单元格的标签,然后淡出更改。 当 tableView 最初通过返回单元格时,如何隐藏这些标签?

问题发生的原因是在行单元格中 UITableView 的返回单元格之后应用了 collection.reload()。

这是代码示例。

  • UITableViewCell 代码
let collectionDatasource = CollectionDataSource()

func configureCell(_ object: CustomClass) {

        //Configure Object for tableView
        self.presentedObject = object
        self.nameLabel.text = object.name

        //Set object and items on collection datasource
        DispatchQueue.main.async {
            let collectionItems = object.collectionItems ?? []
            self.collectionDatasource.object = object
            self.collectionDatasource.items = collectionItems
        }
    }
class CollectionDataSource: NSObject {
    private var collectionView: UICollectionView?
    var items: [CustomItem] = [] {
        didSet {
            DispatchQueue.main.async {
                let changes = [CustomItem].changes(from: oldValue, to: self.items, identifiedBy: ==, comparedBy: <)
                self.collectionView?.apply(changes: changes)
            }
        }
    }
}

最佳答案

UITableView 相比,

UICollectionView 本身是异步工作的。因此,即使您直接在 configureCell 中调用 reload collectionView ,它也会在设置表格后更新集合的单元格(仍然可能导致上述问题)。但是您已将“重新加载”调用添加到 DispatchQueue.main.async 中,这使事情变得更糟。

  1. 如果可能,您应该跳过使用 DispatchQueue.main.async

  2. 您应该在configureCell中将collectionView替换为新的。我建议将 View 添加到与 Collection View 相同大小和位置的单元格中,并在代码中添加 Collection View 。这将保证以前的 Collection View 永远不会出现。 👍

关于ios - UITableView 内的 Collection View 重用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59253793/

相关文章:

ios - 对 iPhone 4S 和 iPhone 5 使用相同的 .xib 文件

ios - 尝试在写入事务之外修改对象

ios - 在 swift : how to add tab bar icons to a regular ViewController storyboard?

ios - UIButton.isSelected 不能 Observable

iphone - 什么时候知道 UITableView 的 contentSize

ios - 使用签名请求从 React Native (iOS) 直接发布到 AWS S3

iOS Objective-C 等待异步进程

ios - NSLayoutConstraint 更改后,systemLayoutSizeFittingSize 不起作用

ios - 强制 UITableView 缓存可重用单元格

ios - 使用具有带 FlowLayout 的 UICollectionView 的单元格滚动 UITableView 时,应用程序崩溃