-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUICollectionView+ClassIdentifiable.swift
66 lines (51 loc) · 2.14 KB
/
UICollectionView+ClassIdentifiable.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
//
// ClassIdentifiable.swift
//
// Created by Nikita Velichkin on 25/01/2020.
// Copyright © 2020 Velichkin Nikita. All rights reserved.
//
import UIKit
// MARK: - UICollectionViewCell
extension UICollectionView {
func register<C: UICollectionViewCell>(cellType: C.Type) where C: ClassIdentifiable {
register(cellType.self, forCellWithReuseIdentifier: cellType.reuseId)
}
func dequeueReusableCell<C: UICollectionViewCell>(_ cellType: C.Type = C.self, forIndexPath indexPath: IndexPath) -> C where C: ClassIdentifiable {
guard
let cell = dequeueReusableCell(withReuseIdentifier: cellType.reuseId, for: indexPath) as? C
else { fatalError(dequeueError(type: cellType)) }
return cell
}
}
// MARK: - UICollectionReusableView
extension UICollectionView {
enum SupplymentaryViewKind {
case header
case footer
var identifier: String {
switch self {
case .header:
return elementKindSectionHeader
case .footer:
return elementKindSectionFooter
}
}
}
func registerView<C: UICollectionReusableView>(ofKind kind: SupplymentaryViewKind, viewType: C.Type) where C: ClassIdentifiable {
register(viewType.self, forSupplementaryViewOfKind: kind.identifier, withReuseIdentifier: viewType.reuseId)
}
func dequeueReusableView<C: UICollectionReusableView>(ofKind kind: SupplymentaryViewKind, _ viewType: C.Type = C.self, forIndexPath indexPath: IndexPath) -> C where C: ClassIdentifiable {
guard let view = dequeueReusableSupplementaryView(ofKind: kind.identifier, withReuseIdentifier: viewType.reuseId, for: indexPath) as? C
else { fatalError(dequeueError(type: viewType)) }
return view
}
}
// MARK: - Dequeue Error
extension UICollectionView {
private func dequeueError<T: ClassIdentifiable>(type: T.Type) -> String {
return """
Failed to dequeue a cell with identifier \(type.reuseId) matching type \(type.self).
Check that the reuseIdentifier is set properly and that you registered the cell beforehand
"""
}
}