-
Notifications
You must be signed in to change notification settings - Fork 1
/
MarvelCharactersCollectionViewController.swift
84 lines (61 loc) · 2.78 KB
/
MarvelCharactersCollectionViewController.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
77
78
79
80
81
82
83
84
//
// MarvelCharactersCollectionViewController.swift
// APIRestDemo
//
// Created by Adrian Iraizos Mendoza on 31/1/24.
//
import SwiftUI
final class MarvelCharactersCollectionViewController: UICollectionViewController {
let modelLogic = MarvelCharactersModelLogic.shared
lazy var dataSource: UICollectionViewDiffableDataSource<Int,MarvelCellCharacter> = {
UICollectionViewDiffableDataSource<Int,MarvelCellCharacter>(collectionView: collectionView) { [self] collectionView, indexPath, character in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "marvelCharacterCell", for: indexPath)
cell.contentConfiguration = UIHostingConfiguration {
MarvelCharacterCellView(character: character)
}
return cell
}
}()
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
collectionView.dataSource = dataSource
dataSource.apply(modelLogic.snapshot,animatingDifferences: true)
NotificationCenter.default.addObserver(forName: .marvelCharacters, object: nil, queue: .main) { [weak self] _ in
self?.collectionView.collectionViewLayout.invalidateLayout()
self?.collectionView.reloadData()
if let snapshot = self?.modelLogic.snapshot {
self?.dataSource.apply(snapshot, animatingDifferences: true)
self?.activityIndicator.stopAnimating()
}
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let marvelCharacter = dataSource.itemIdentifier(for: indexPath) else { return }
modelLogic.toggleFavorite(marvelCharacter)
}
override func viewWillAppear(_ animated: Bool) {
Task {
await modelLogic.addCharacters()
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if maximumOffset - currentOffset <= 50 {
activityIndicator.startAnimating()
Task {
await modelLogic.addCharacters()
activityIndicator.stopAnimating()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: .marvelCharacters, object: nil)
}
}
extension Notification.Name {
static let marvelCharacters = Notification.Name("MRVLCHAR")
static let marvelFavoritesChar = Notification.Name("MRVLFAV")
}