CellProvider Closure 永远不会为 UICollectionViewDiffableDataSource 执行

CellProvider Closure never gets executed for UICollectionViewDiffableDataSource

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

}

这是因为您没有在任何地方追加项目,所以您的快照是空的。当您追加一个部分时,您只是将该部分作为标识符追加。您没有追加该部分及其所有项目。

查看文档 here