-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathExpandable.swift
More file actions
70 lines (51 loc) · 1.99 KB
/
Copy pathExpandable.swift
File metadata and controls
70 lines (51 loc) · 1.99 KB
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
import UIKit
public protocol Expandable {
associatedtype ViewModelType: ExpandableCellViewModel
var viewModel: ViewModelType? { get }
func configureAppearance(isCollapsed: Bool)
}
extension Expandable where Self: UITableViewCell & ConfigurableCell {
public func initState() {
guard let viewModel = viewModel else {
return
}
changeState(isCollapsed: viewModel.isCollapsed)
}
private func changeState(isCollapsed: Bool) {
// layout to get right frames, frame of bottom subview can be used to get expanded height
layoutIfNeeded()
// apply changes
configureAppearance(isCollapsed: isCollapsed)
layoutIfNeeded()
}
public func toggleState(animated: Bool = true,
animationDuration: TimeInterval = 0.3) {
guard let tableView = tableView,
let viewModel = viewModel else {
return
}
let contentOffset = tableView.contentOffset
if animated {
UIView.animate(withDuration: animationDuration,
animations: { [weak self] in
self?.applyChanges(isCollapsed: !viewModel.isCollapsed)
}, completion: { _ in
viewModel.isCollapsed.toggle()
})
} else {
applyChanges(isCollapsed: !viewModel.isCollapsed)
viewModel.isCollapsed.toggle()
}
tableView.beginUpdates()
tableView.endUpdates()
tableView.setContentOffset(contentOffset, animated: false)
}
private func applyChanges(isCollapsed: Bool) {
changeState(isCollapsed: isCollapsed)
if let indexPath = indexPath,
let tableDirector = (tableView?.delegate as? TableDirector),
let cellHeightCalculator = tableDirector.rowHeightCalculator as? ExpandableCellHeightCalculator {
cellHeightCalculator.updateCached(height: height(layoutType: Self.layoutType), for: indexPath)
}
}
}