Skip to content

Instantly share code, notes, and snippets.

@cocuroci
Created February 8, 2023 13:53
Show Gist options
  • Save cocuroci/1c1af121a6427284036ed54f5ea0a58e to your computer and use it in GitHub Desktop.
Save cocuroci/1c1af121a6427284036ed54f5ea0a58e to your computer and use it in GitHub Desktop.
UICollectionViewCompositionalLayout
import UIKit
final class HomeViewController: UIViewController {
private typealias DataSource = UICollectionViewDiffableDataSource<Int, String>
private typealias Snapshot = NSDiffableDataSourceSnapshot<Int, String>
private lazy var dataSource: DataSource = {
let cellHandler = UICollectionView.CellRegistration { (cell: UICollectionViewListCell, indexPath: IndexPath, itemIdentifier: String) in
var config = cell.defaultContentConfiguration()
config.text = itemIdentifier
cell.contentConfiguration = config
}
let dataSource = DataSource(collectionView: collectionView) { collectionView, indexPath, itemIdentifier in
collectionView.dequeueConfiguredReusableCell(using: cellHandler, for: indexPath, item: itemIdentifier)
}
return dataSource
}()
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeCollectionViewLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.register(UICollectionViewListCell.self, forCellWithReuseIdentifier: "Cell")
return collectionView
}()
private func makeCollectionViewLayout() -> UICollectionViewCompositionalLayout {
UICollectionViewCompositionalLayout { section, environment in
let itemLayout = NSCollectionLayoutItem(
layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .estimated(200))
)
let groupLayout: NSCollectionLayoutGroup = .horizontal(
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(200)),
subitems: [itemLayout]
)
let sectionLayout = NSCollectionLayoutSection(group: groupLayout)
return sectionLayout
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
var snapshot = Snapshot()
snapshot.appendSections([0])
snapshot.appendItems(["1d ad sad sds dsad s dssad sfdf dsdddfsf df dsfsdf sfsd","2","3","4","5","6"])
dataSource.apply(snapshot)
collectionView.dataSource = dataSource
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment