DiffableDataSource:快照不会重新加载页眉和页脚

问题描述 投票:1回答:1

我正在将UICollectionViewDiffableDataSource用于UICollectionView以显示多个部分中的内容。

[我使用的是在WWDC'19上引入的集合视图组成布局和可扩散数据源link,以呈现UICollectionView的多节布局

我有一个简单的设置,每个节的标题显示该节中的项目数,而页脚显示该节中所有项目的摘要。

第1节标题-> 2020年1月-5次旅行第1节项目1->行程1第1节项目2->行程2第1节项目3->行程3第1节项目4->行程4第1节项目5->行程5

现在删除行程,DiffableDataSource将通过动画更新更改,但不会重新加载各节的标题。看起来不一致。例如。如果行程4被删除,则标题仍显示该部分中有5个行程。如何让标头也与DiffableDataSource重新加载?

作为临时解决方案,我只是打电话给collectionView.reloadData()经过一段延迟,显示了Diffing动画,然后我重新加载了数据,这也迫使页眉也重新加载。

private func configureTripDataSource(){
    tripDataSource = UICollectionViewDiffableDataSource<MonthSection, Trip>(collectionView: tripsCollectionView, cellProvider: { (collectionView, indexPath, trip) -> UICollectionViewCell? in

        // Get a cell of the desired kind.
        guard let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: TripInfoCell.reuseIdentifier,
            for: indexPath) as? TripInfoCell else { fatalError("Cannot create new TripInfoCell") }

        // Populate the cell with our item description.
        cell.trip = trip

        // Return the cell.
        return cell

    })

    tripDataSource.supplementaryViewProvider = {
       [weak self] (collectionView: UICollectionView, kind: String, indexPath: IndexPath) -> UICollectionReusableView? in

        guard let self = self else {return nil}

        if kind == TripsController.tripsMonthSectionHeaderElementKind{

            // Get a supplementary view of the desired kind.
            guard let header = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: TripSectionHeaderCell.reuseIdentifier,
                for: indexPath) as? TripSectionHeaderCell else { fatalError("Cannot create new header") }

            // setup header

            let currentSnapShot = self.tripDataSource.snapshot()
            let tripMonthSection = currentSnapShot.sectionIdentifiers[indexPath.section]

            header.titleLabel.text = tripMonthSection.title
            header.subtitleLabel.text = "\(tripMonthSection.trips.count) Trips"

            return header

        } else {
            return UICollectionReusableView()
        }

    }

    var snapshot = NSDiffableDataSourceSnapshot<MonthSection, Trip>()

    let allSections = self.tripsStore.monthSections
    snapshot.appendSections(allSections)
    for section in allSections{
        snapshot.appendItems(section.trips, toSection: section)
    }

    self.tripDataSource.apply(snapshot, animatingDifferences: true)
}
ios swift uicollectionview uicollectionviewlayout diffabledatasource
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.