NPTableAnimator
要求
iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.0 / Xcode 9+
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
。
导入库以使用
import NPTableAnimator
首先,你需要将你的视图模型适配到 TableAnimatorCell 协议
struct MyViewModel: TableAnimatorCell {
let id: Int
var hashValue: Int {
return id.hashValue
}
var updateField: Date
static func == (lhs: MyViewModel, rhs: MyViewModel) -> Bool {
return lhs.id == rhs.id
}
}
为了正确且快速地计算动画,你的视图模型应该适配到 Equatable 和 Hashable 协议。这样,你可以告诉动画器如何计算单元格之间的变化,但表格也有章节,因此你必须向动画器提供这些信息。你的章节应该适配到 TableAnimatorSection 协议。
• 注意:即使你只有一个章节,你也必须提供章节。只需为 updateField 设置默认值,并在比较函数中将 true 传递即可。
struct MySection: TableAnimatorSection {
let id: Int
var cells: [MyCell]
var updateField: Int
static func == (lhs: MySection, rhs: MySection) -> Bool {
return lhs.id == rhs.id
}
}
然后,你应该创建一个用于计算动画的动画实例,并构建两个列表之间的动画
let animator = TableAnimator<MySection>()
let animations = try! animator.buildAnimations(from: currentList, to: newList)
animations 结构包含章节和单元格的插入、删除、更新和移动,你可以将其传递以进行更新。
tableView.beginUpdates()
self.currentList = newList
tableView.insertSections(animations.sections.toInsert, with: .fade)
tableView.deleteSections(animations.sections.toDelete, with: .fade)
tableView.reloadSections(animations.sections.toUpdate, with: .fade)
for (from, to) in animations.sections.toMove {
tableView.moveSection(from, toSection: to)
}
tableView.reloadRows(animations.cells.toUpdate, with: .fade)
tableView.insertRows(at: animations.cells.toInsert, with: .fade)
tableView.deleteRows(at: animations.cells.toDelete, with: .fade)
tableView.reloadRows(at: animations.cells.toUpdate, with: .fade)
for (from, to) in animations.cells.toMove {
tableView.moveRow(at: from, to: to)
}
tableView.endUpdates()
// You should call .reloadRows(_:with:) in another update circle cause of UITableView update bugs...
// Animator provide all updates in toUpdate only if toInsert, toDelete and toUpdate are empty
// otherwise animator provides toDeferredUpdate array based on new cell indexes.
tableView.beginUpdates()
tableView.reloadRows(animations.cells.toDeferredUpdate, with: .fade)
tableView.endUpdates()
为了您的舒适,动画器可能会计算并应用列表。如果您使用上述代码,在更新动画期间将看到奇特的闪烁。这不是致命的,但不太酷。因此,动画器可能正确地将更改应用到您的表格上。为此,您可以使用以下代码
var currentList = [MySection]()
// Note: - currentList **not** changed to newList instantly. That function only start applying and
// adding request for change to newList into a queue.
tableView.apply(owner: self,
newList: newList,
animator: animator,
animated: true,
getCurrentListBlock: { $0.currentList },
setNewListBlock: { $0.currentList = $1 },
rowAnimation: .fade)
安装
NPTableAnimator 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile即可
pod "NPTableAnimator"
作者
Nikita Patskov,[email protected]
许可协议
NPTableAnimator 在 MIT 许可协议下可用。更多信息请参阅 LICENSE 文件。