This repository was archived by the owner on Dec 5, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathUITableView+Extensions.swift
executable file
·95 lines (80 loc) · 2.66 KB
/
UITableView+Extensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// UITableView+Extensions.swift
// DeepDiff
//
// Created by Khoa Pham.
// Copyright © 2018 Khoa Pham. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
public extension UITableView {
/// Animate reload in a batch update
///
/// - Parameters:
/// - changes: The changes from diff
/// - section: The section that all calculated IndexPath belong
/// - insertionAnimation: The animation for insert rows
/// - deletionAnimation: The animation for delete rows
/// - replacementAnimation: The animation for reload rows
/// - updateData: Update your data source model
/// - completion: Called when operation completes
func reload<T: DiffAware>(
changes: [Change<T>],
section: Int = 0,
insertionAnimation: UITableView.RowAnimation = .automatic,
deletionAnimation: UITableView.RowAnimation = .automatic,
replacementAnimation: UITableView.RowAnimation = .automatic,
updateData: () -> Void,
completion: ((Bool) -> Void)? = nil) {
let changesWithIndexPath = IndexPathConverter().convert(changes: changes, section: section)
unifiedPerformBatchUpdates({
updateData()
self.insideUpdate(
changesWithIndexPath: changesWithIndexPath,
insertionAnimation: insertionAnimation,
deletionAnimation: deletionAnimation
)
}, completion: { finished in
completion?(finished)
})
// reloadRows needs to be called outside the batch
outsideUpdate(changesWithIndexPath: changesWithIndexPath, replacementAnimation: replacementAnimation)
}
// MARK: - Helper
private func unifiedPerformBatchUpdates(
_ updates: (() -> Void),
completion: (@escaping (Bool) -> Void)) {
if #available(iOS 11, tvOS 11, *) {
performBatchUpdates(updates, completion: completion)
} else {
beginUpdates()
updates()
endUpdates()
completion(true)
}
}
private func insideUpdate(
changesWithIndexPath: ChangeWithIndexPath,
insertionAnimation: UITableView.RowAnimation,
deletionAnimation: UITableView.RowAnimation) {
changesWithIndexPath.deletes.executeIfPresent {
deleteRows(at: $0, with: deletionAnimation)
}
changesWithIndexPath.inserts.executeIfPresent {
insertRows(at: $0, with: insertionAnimation)
}
changesWithIndexPath.moves.executeIfPresent {
$0.forEach { move in
moveRow(at: move.from, to: move.to)
}
}
}
private func outsideUpdate(
changesWithIndexPath: ChangeWithIndexPath,
replacementAnimation: UITableView.RowAnimation) {
changesWithIndexPath.replaces.executeIfPresent {
reloadRows(at: $0, with: replacementAnimation)
}
}
}
#endif