Skip to content

Instantly share code, notes, and snippets.

@SebastianBoldt
Created March 12, 2020 19:56
Show Gist options
  • Save SebastianBoldt/e8be81a90941dff7e61b65f247552d8d to your computer and use it in GitHub Desktop.
Save SebastianBoldt/e8be81a90941dff7e61b65f247552d8d to your computer and use it in GitHub Desktop.
import UIKit
enum Section {
case section1
case section2
}
struct Item: Hashable {
let color: UIColor
}
class ViewController: UIViewController {
@IBOutlet var collectionview: UICollectionView! {
didSet {
collectionview.delegate = self
}
}
lazy var dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: self.collectionview,
cellProvider: self.cellProvider)
lazy var cellProvider: (UICollectionView, IndexPath, Item) -> UICollectionViewCell? = { collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = item.color
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
let items1 = [
Item(color: .green),
Item(color: .red),
Item(color: .blue)
]
let items2 = [
Item(color: .yellow),
Item(color: .orange),
Item(color: .purple)
]
addItems(items: items1, to: .section1)
addItems(items: items2, to: .section2)
}
}
extension ViewController {
func addItems(items: [Item], to section: Section) {
var snapshot = dataSource.snapshot()
snapshot.appendSections([section])
snapshot.appendItems(items, toSection: section)
dataSource.apply(snapshot)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment