1

当我使用 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!")
            }
        }
    }
4

1 回答 1

1

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

这个惰性 var dataSource 导致错误:

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 初始化程序中的操作。

于 2020-05-02T09:43:04.497 回答