DiffableWithReload

为可差异数据源自动调用 reloadItems(_:)

新的 (iOS 13+) 可差异数据源是TableView和CollectionView使用起来更简便的一大进步。但有一种操作例外:条目重载。

为什么

现代应用程序架构将数据存储在某种 ViewModel 或 ViewStore 中(The Composable ArchitectureCombineFeedback,以及许多其他的),而 UI 只是观察数据。

ViewModel/ViewStore 非常可能:

得益于可差异数据源 UITableViewDiffableDataSourceUICollectionViewDiffableDataSource,以动画方式更新 table/collection view 非常容易

唯一麻烦的步骤是最后一个:哪些条目必须重新加载?

DiffableWithReload 自动识别需要重新加载的条目,因此您无需关心重新加载。需要重新加载的单元格(且仅这些单元格)会自动重新加载(当应用 snapshot 时)。

DiffableWithReload 子类化了 UITableViewDiffableDataSourceUICollectionViewDiffableDataSource(仍然是泛型类),因此您可以将它们与您的数据类型一起使用。

对于基本使用,可以使用

TableViewDiffableReloadingDataSource<SectionIdentifierType: Hashable, ItemIdentifierType: Hashable, EquatableCellContent: Equatable>

CollectionViewDiffableReloadingDataSource<SectionIdentifierType: Hashable, ItemIdentifierType: Hashable, EquatableCellContent: Equatable>

对于高级使用,当您需要(例如)数据锁定时,可以使用这些子类

TableViewDiffableDelegatingDataSource<SectionIdentifierType: Hashable, ItemIdentifierType: Hashable, Delegate: ReloadingDataSourceDelegate, EquatableCellContent: Equatable>

CollectionViewDiffableDelegatingDataSource<SectionIdentifierType: Hashable, ItemIdentifierType: Hashable, Delegate: ReloadingDataSourceDelegate, EquatableCellContent: Equatable>

示例

// change data in the cars array
cars.changeColorOfAllCars(brand: .volkswagen)
// apply the current snapshot
let snapshot = diffableDataSource.snapshot()
// items for reload are automatically created
diffableDataSource.applyWithItemsReloadIfNeeded(snapshot, animatingDifferences: true)

强烈建议查看示例代码。示例 iOS 应用程序中有 3 个选项卡

底层原理(它是如何工作的)

安装说明

CocoaPods

要使用 CocoaPods 将 Toast-Swift 集成到您的 Xcode 项目中,请在您的 Podfile 中指定它

pod 'DiffableWithReload', '~> 1.0.0'

并在您的代码中使用 import DiffableWithReload

Swift Package Manager

当使用 Xcode 11 或更高版本时,您可以通过转到您的项目设置 > Swift Packages 并通过提供 GitHub URL 来添加存储库,从而安装 DiffableWithReload。 或者,您可以转到 File > Swift Packages > Add Package Dependencies...

兼容性