从未对UICollectionViewDiffableDataSource执行CellProvider闭包


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)
}    
}

这是因为您没有将项目追加到任何位置,因此您的快照是空的。当您附加一个节时,您只是将该节作为一个标识符附加。您不是在附加该节及其所有项目。

请参阅此处的文档。

最新更新