Skip to content

Instantly share code, notes, and snippets.

@erikfloresq
Created July 14, 2024 15:34
Show Gist options
  • Save erikfloresq/ecbf15d96835415c867861091e3dbd8b to your computer and use it in GitHub Desktop.
Save erikfloresq/ecbf15d96835415c867861091e3dbd8b to your computer and use it in GitHub Desktop.
class TableCollectionViewController: UIViewController {
let collectionView : UICollectionView = {
let layout = UICollectionViewCompositionalLayout.list(using: UICollectionLayoutListConfiguration(appearance: .plain))
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
lazy var collectionDataSource = CollectionDataSource(collectionView: collectionView)
override func viewDidLoad() {
super.viewDidLoad()
title = "TableCollection"
setup()
}
func setup() {
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
let button = UIBarButtonItem(image: .add, style: .plain, target: self, action: #selector(addItem))
navigationItem.rightBarButtonItem = button
collectionDataSource.snapshotData(items: (1...2).map{ Item(text: "Demo \($0)") })
}
@objc
func addItem() {
let item = Item(text: "collection item")
collectionDataSource.snapshotData(items: [item])
}
}
class ItemCollectionCell: UICollectionViewCell {
override var reuseIdentifier: String? {
"ItemCollectionCell"
}
}
class CollectionDataSource {
typealias DataSource = UICollectionViewDiffableDataSource<Section, Item>
typealias Diffable = NSDiffableDataSourceSnapshot<Section, Item>
private let collectionView: UICollectionView
let itemCellRegistration = UICollectionView.CellRegistration<ItemCollectionCell, Item> { cell, indexPath, item in
var config = UIListContentConfiguration.subtitleCell()
config.text = item.text
cell.contentConfiguration = config
}
lazy var dataSource = DataSource(collectionView: collectionView) { [weak self] collectionView, indexPath, itemIdentifier in
guard let self else { return UICollectionViewCell() }
let cell = collectionView.dequeueConfiguredReusableCell(using: itemCellRegistration, for: indexPath, item: itemIdentifier)
return cell
}
var diffable = Diffable()
init(collectionView: UICollectionView) {
self.collectionView = collectionView
setup()
}
func setup() {
diffable.appendSections([.main])
}
func snapshotData(items: [Item]) {
diffable.appendItems(items, toSection: .main)
dataSource.apply(diffable)
}
}
struct Item: Hashable, Identifiable {
let id: UUID = UUID()
let text: String
}
enum Section {
case main
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment