新的 (iOS 13+) 可差异数据源是TableView和CollectionView使用起来更简便的一大进步。但有一种操作例外:条目重载。
现代应用程序架构将数据存储在某种 ViewModel 或 ViewStore 中(The Composable Architecture,CombineFeedback,以及许多其他的),而 UI 只是观察数据。
ViewModel/ViewStore 非常可能:
得益于可差异数据源 UITableViewDiffableDataSource 和 UICollectionViewDiffableDataSource,以动画方式更新 table/collection view 非常容易
唯一麻烦的步骤是最后一个:哪些条目必须重新加载?
DiffableWithReload 自动识别需要重新加载的条目,因此您无需关心重新加载。需要重新加载的单元格(且仅这些单元格)会自动重新加载(当应用 snapshot 时)。
DiffableWithReload 子类化了 UITableViewDiffableDataSource 和 UICollectionViewDiffableDataSource(仍然是泛型类),因此您可以将它们与您的数据类型一起使用。
对于基本使用,可以使用
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 个选项卡
EquatableCellContent
(符合 Equatable
)EquatableCellContent
)。 同样,它可以是符合 Equatable
的任何类型,但有两个方便的结构体可以创建可相等的内容EncodableContent
从指定的属性创建 Data?
值:Data?
是显示内容的唯一标识符,可以很容易地从您的底层数据的任何 Encodable
属性创建。提供的 data
值是可选的,因为 encode(to:)
可能会抛出异常。 在这种情况下,单元格总是会被重新加载。HashableContent
从指定的属性创建 Int
(哈希值):hashValue
是显示内容不是那么唯一的标识符,但是可能已经足够好。 默认选择应该是 EncodableContent
。要使用 CocoaPods 将 Toast-Swift 集成到您的 Xcode 项目中,请在您的 Podfile
中指定它
pod 'DiffableWithReload', '~> 1.0.0'
并在您的代码中使用 import DiffableWithReload
。
当使用 Xcode 11 或更高版本时,您可以通过转到您的项目设置 > Swift Packages
并通过提供 GitHub URL 来添加存储库,从而安装 DiffableWithReload
。 或者,您可以转到 File
> Swift Packages
> Add Package Dependencies...
1.0.0
需要 Swift 5