Skip to content

Instantly share code, notes, and snippets.

@1amageek
Created March 15, 2020 15:36
Show Gist options
  • Save 1amageek/a464b387996ea882703ef36959d73622 to your computer and use it in GitHub Desktop.
Save 1amageek/a464b387996ea882703ef36959d73622 to your computer and use it in GitHub Desktop.
//
// ProductsViewController.swift
// Created by nori on 2020/03/15.
// Copyright © 2020 nori. All rights reserved.
//
import UIKit
import Instantiate
import Firebase
import Ballcap
import SwiftUI
import SwiftUICell
class ProductsViewController: DataSourceViewController<Commerce.Product>, UICollectionViewDelegate {
enum Section: Int {
case main
}
struct _Cell: Cell {
var text: String
var body: some View {
Text(text)
}
}
lazy var dataSource: UICollectionViewDiffableDataSource<Section, ItemIdentifier> = {
let dataSource = UICollectionViewDiffableDataSource<Section, ItemIdentifier>(collectionView: self.collectionView) { (collectionView, indexPath, id) -> UICollectionViewCell? in
guard let data: Commerce.Product.Model = self.products[indexPath.item].data else { return nil }
let cell = SwiftUICell<_Cell>.dequeue(
collectionView: collectionView,
indexPath: indexPath,
contentView: _Cell(text: data.name), parent: self)
return cell
}
return dataSource
}()
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
layout.scrollDirection = .vertical
let view: UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
view.alwaysBounceVertical = false
view.backgroundColor = .secondarySystemBackground
view.delegate = self
view.register(content: _Cell.self)
return view
}()
var products: [Commerce.Product] = []
override func loadView() {
super.loadView()
self.view.addSubview(collectionView)
self.view.backgroundColor = .secondarySystemBackground
}
override func viewDidLoad() {
super.viewDidLoad()
var snapshot: NSDiffableDataSourceSnapshot<Section, ItemIdentifier> = NSDiffableDataSourceSnapshot()
snapshot.appendSections([.main])
self.dataSource.apply(snapshot, animatingDifferences: true)
self._dataSource
.onChanged({ [weak self] (querySnapstho, dataSourceSnapshot) in
guard var snapshot: NSDiffableDataSourceSnapshot<Section, ItemIdentifier> = self?.dataSource.snapshot() else { return }
snapshot.deleteItems(dataSourceSnapshot.before.map { ItemIdentifier(rawValue: $0.path) })
snapshot.appendItems(dataSourceSnapshot.after.map { ItemIdentifier(rawValue: $0.path) }, toSection: .main)
self?.dataSource.apply(snapshot, animatingDifferences: true)
})
.get()
}
}
struct _Cell_Previews: PreviewProvider {
static var previews: some View {
ProductsViewController._Cell(text: "text")
.previewLayout(.fixed(width: UIScreen.main.bounds.width, height: 120))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment