-
Notifications
You must be signed in to change notification settings - Fork 52
/
MultiIndexHitsCollectionViewDataSource.swift
73 lines (57 loc) · 2.26 KB
/
MultiIndexHitsCollectionViewDataSource.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
//
// MultiIndexHitsCollectionViewDataSource.swift
// InstantSearch
//
// Created by Vladislav Fitc on 02/08/2019.
//
import Foundation
import UIKit
open class MultiIndexHitsCollectionViewDataSource: NSObject {
private typealias CellConfigurator = (UICollectionView, Int) throws -> UICollectionViewCell
public weak var hitsSource: MultiIndexHitsSource?
private var cellConfigurators: [Int: CellConfigurator]
override init() {
cellConfigurators = [:]
super.init()
}
public func setCellConfigurator<Hit: Codable>(forSection section: Int,
templateCellProvider: @escaping () -> UICollectionViewCell = { return .init() },
_ cellConfigurator: @escaping CollectionViewCellConfigurator<Hit>) {
cellConfigurators[section] = { [weak self] (collectionView, row) in
guard let dataSource = self else {
return .init()
}
guard let hitsSource = dataSource.hitsSource else {
fatalError("Missing hits source")
}
guard let hit: Hit = try hitsSource.hit(atIndex: row, inSection: section) else {
return templateCellProvider()
}
return cellConfigurator(collectionView, hit, IndexPath(row: row, section: section))
}
}
}
extension MultiIndexHitsCollectionViewDataSource: UICollectionViewDataSource {
open func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let hitsSource = hitsSource else {
fatalError("Missing hits source")
}
return hitsSource.numberOfSections()
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let hitsSource = hitsSource else {
fatalError("Missing hits source")
}
return hitsSource.numberOfHits(inSection: section)
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cellConfigurator = cellConfigurators[indexPath.section] else {
fatalError("No cell configurator found for section \(indexPath.section)")
}
do {
return try cellConfigurator(collectionView, indexPath.row)
} catch let error {
fatalError("\(error)")
}
}
}