Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class ViewController: UIViewController {
var items = Array(0...100).map { String($0) }
var collectionView : UICollectionView!
private lazy var dataSource = makeDataSource()
override func viewDidLoad() {
super.viewDidLoad()
let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
let layout = UICollectionViewCompositionalLayout.list(using: config)
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
self.view.addSubview(collectionView)
//add autolayout constraints
collectionView.dataSource = dataSource
var snapshot = NSDiffableDataSourceSnapshot<String,String>()
snapshot.appendSections(["Section 1"])
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: true)
}
func makeDataSource() -> UICollectionViewDiffableDataSource<String, String> {
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, String> { cell, indexPath, name in
var content = cell.defaultContentConfiguration()
content.text = name
cell.contentConfiguration = content
}
return UICollectionViewDiffableDataSource<String, String>(
collectionView: collectionView,
cellProvider: { collectionView, indexPath, item in
collectionView.dequeueConfiguredReusableCell(
using: cellRegistration,
for: indexPath,
item: item
)
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment