-
Notifications
You must be signed in to change notification settings - Fork 0
/
CollectionViewControllerGenerics.swift
76 lines (60 loc) · 2.09 KB
/
CollectionViewControllerGenerics.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
//
// CollectionViewControllerGenerics.swift
// iBadoo
//
// Created by Sergiu on 8/14/18.
// Copyright © 2018 Sergiu Suru. All rights reserved.
//
import UIKit
class BaseCollectionViewController<T: BasicCollectionCell<S>, S>: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
var items = [S]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
collectionView?.backgroundColor = .white
collectionView?.register(T.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BasicCollectionCell<S>
cell.cellItem = items[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 50)
}
}
class BasicCollectionCell<U>: UICollectionViewCell {
var cellItem: U!
}
struct Cat {
let name: String
}
class CatCell: BasicCollectionCell<Cat> {
let myLabelText: UILabel = {
let label = UILabel()
return label
}()
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = .red
addSubview(myLabelText)
myLabelText.fillSuperView()
}
override var cellItem: Cat! {
didSet {
myLabelText.text = cellItem.name
}
}
}
class SomeController: BaseCollectionViewController<CatCell, Cat> {
override func viewDidLoad() {
super.viewDidLoad()
items = [Cat(name: "Miauuuuu"),
Cat(name: "Brrrrrrrr"),
Cat(name: "Hrrrrr")]
}
}