Skip to content

Instantly share code, notes, and snippets.

@anupamchugh
Last active June 9, 2022 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupamchugh/24ab85a1d005aac01f4385185981437b to your computer and use it in GitHub Desktop.
Save anupamchugh/24ab85a1d005aac01f4385185981437b to your computer and use it in GitHub Desktop.
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