【问题标题】:CollectionView using NSDiffableDataSource with UICollectionViewFlowLayoutCollectionView 使用 NSDiffableDataSource 和 UICollectionViewFlowLayout
【发布时间】:2020-08-16 16:43:08
【问题描述】:

当我使用 UICollectionView 和 UICollectionViewFlowLayout 集时。然后尝试通过

应用数据源的快照
// load initial data
        reloadDataSource()

        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
            self.reloadDataSource(animating: true)
        }

延迟 3 秒后应用第二个快照时出现崩溃。 崩溃仅在动画时发生:true

如果我将动画设置为 false,则不会发生崩溃,但如果留空则集合视图。

这是应用数据源的方法

extension CollectionViewController {

    func reloadDataSource(animating: Bool = false) {

        print("reloading data source with snapshot -> \(snapshot.numberOfItems)")

        self.dataSource.apply(self.snapshot, animatingDifferences: animating) {
            print("applying snapshot completed!")
        }
    }
}

数据源只是

let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)

您可以玩的完整项目(可能会随着时间而变化):https://github.com/michzio/SwifUICollectionView

更新

我试图简化示例并执行类似的操作,但它无法正常工作。似乎将 .apply() 移动到后台队列,其他队列导致collectionview中的数据为空

func reloadDataSource(animating: Bool = false) {

        print("reloading data source with snapshot -> \(snapshot.numberOfItems)")
        diffQueue.async {
            var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
            snapshot.appendSections([.categories])
            snapshot.appendItems(Item.categoryItems)

            self.dataSource.apply(snapshot, animatingDifferences: animating) {
                print("applying snapshot completed!")
            }
        }
    }

【问题讨论】:

    标签: uicollectionview swiftui uicollectionviewflowlayout nsdiffabledatasourcesnapshot


    【解决方案1】:

    好吧,我似乎找到了通过应用新快照更新数据源的所有错误的原因

    这个惰性 var 数据源导致错误:

    private(set) lazy var dataSource: UICollectionViewDiffableDataSource<Section, Item> = {
            let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)
            //dataSource.supplementaryViewProvider = supplementaryViewProvider
            return dataSource
        }()
    

    我已经改成

    private(set) var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
    

    在 viewDidLoad() 中的 configureCollectionView 之后 现在我正在调用 configureDataSource() 来执行惰性 var 初始化程序中的操作。

    【讨论】:

      猜你喜欢
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多