-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostsCollectionViewDataSource.swift
More file actions
78 lines (64 loc) · 2.46 KB
/
PostsCollectionViewDataSource.swift
File metadata and controls
78 lines (64 loc) · 2.46 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
71
72
73
74
75
76
77
78
//
// PostsCollectionViewDataSource.swift
// PerfectlyCrafted
//
// Created by Ashli Rankin on 10/13/19.
// Copyright © 2019 Ashli Rankin. All rights reserved.
//
import UIKit
/// The data source of the `PostCollectionView`.
final class PostsCollectionViewDataSource: NSObject {
enum Section {
case main
}
typealias CellConfiguration = (UICollectionView, IndexPath, Post) -> UICollectionViewCell
private let cellConfiguration: CellConfiguration
private lazy var dataSource: UICollectionViewDiffableDataSource<Section, Post>? = {
guard let collectionView = collectionView else {
return nil
}
let dataSource = UICollectionViewDiffableDataSource<Section, Post>(collectionView: collectionView) { (collectionView, indexPath, post) -> UICollectionViewCell? in
self.cellConfiguration(collectionView, indexPath, post)
}
return dataSource
}()
private weak var collectionView: UICollectionView?
/// Creates a new instance of `PostsCollectionViewDataSource`
/// - Parameters:
/// - collectionView: The collection view
/// - cellConfiguration: the cell configuration
init(collectionView: UICollectionView, cellConfiguration: @escaping CellConfiguration) {
self.collectionView = collectionView
self.cellConfiguration = cellConfiguration
}
/// Updates the data source's snapshot.
/// - Parameter snapshot: The snapshot.
func updateSnapshot(_ snapshot: NSDiffableDataSourceSnapshot<Section, Post>) {
dataSource?.apply(snapshot)
}
var items: Int {
guard let dataSource = dataSource else {
return 0
}
return dataSource.snapshot().numberOfItems
}
/// Provides an `Item` for the given `IndexPath`.
/// - Parameter indexPath: The `IndexPath` of the desired item.
func item(for indexPath: IndexPath) -> Post? {
return dataSource?.itemIdentifier(for: indexPath)
}
/// Reloads the provided item.
/// - Parameter item: The `Item` to reload.
func reload(item: Post) {
reload(items: [item])
}
/// Reloads the provided items.
/// - Parameter items: The array of `Item`s to reload.
func reload(items: [Post]) {
guard var currentSnapshot = dataSource?.snapshot() else {
return
}
currentSnapshot.reloadItems(items)
dataSource?.apply(currentSnapshot)
}
}