class PropertyCollViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var sections = Person.getSectionData()
typealias PropertyDataSource = UICollectionViewDiffableDataSource<Person.Section, Property>
typealias PropertySnapshot = NSDiffableDataSourceSnapshot<Person.Section, Property>
private var dataSource: PropertyDataSource!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Collections"
collectionView.collectionViewLayout = configureLayout()
configureDataSource()
}
func configureLayout() -> UICollectionViewCompositionalLayout {
let size = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(44)
)
let item = NSCollectionLayoutItem(layoutSize: size)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .absolute(44))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
section.interGroupSpacing = 0
return UICollectionViewCompositionalLayout(section: section)
}
func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Person.Section, Property>(collectionView: collectionView, cellProvider: { (collectionView, indexpath, property) -> UICollectionViewCell? in
print("Cool")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PropertyViewCell", for: indexpath) as? PropertyViewCell
cell?.titleLabel.text = property.asset.name
cell?.backgroundColor = .red
return cell
})
dataSource.supplementaryViewProvider = { (collectionView, kind, indexpath) in
guard kind == UICollectionView.elementKindSectionHeader else {
return nil
}
guard let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderView", for: indexpath) as? HeaderView else {
fatalError()
}
let section = self.dataSource.snapshot().sectionIdentifiers[indexpath.section]
view.sectionTitle.text = section.id.rawValue
view.backgroundColor = .red
return view
}
var snapShot = PropertySnapshot()
snapShot.appendSections(sections)
dataSource.apply(snapShot, animatingDifferences: true)
}
}