4

我正在尝试使用最新的 UICollectionViewCompositionalLayout 来使用 UICollectionViewDiffableDataSource 显示分页数据。我想在该部分上方显示一个粘性标题,即使在从网络加载下一页数据时也始终保持在顶部。我注意到粘性标题没有按预期工作,而是在后台下载数据时感觉生涩并应用新快照。我能够使用 Apple在此处共享的示例应用程序重现此问题

这是重现该问题的代码:

func layout() -> UICollectionViewLayout {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                         heightDimension: .fractionalHeight(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                          heightDimension: .absolute(44))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

    let section = NSCollectionLayoutSection(group: group)
    section.interGroupSpacing = 5
    section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)

    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
        layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                          heightDimension: .estimated(44)),
        elementKind: sectionHeaderElementKind,
        alignment: .top)
    sectionHeader.pinToVisibleBounds = true
    sectionHeader.zIndex = 2
    section.boundarySupplementaryItems = [sectionHeader]

    let layout = UICollectionViewCompositionalLayout(section: section)
    return layout
}

上面的代码片段为 UICollectionViewCompositionalLayout 提供了部分标题,该部分标题固定到顶部的可见边界。

func setUpCollectionView() {
    let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout())
    collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    collectionView.backgroundColor = .systemBackground
    collectionView.register(ListCell.self, forCellWithReuseIdentifier: ListCell.reuseIdentifier)
    collectionView.register(TitleSupplementaryView.self,
                forSupplementaryViewOfKind: sectionHeaderElementKind,
                withReuseIdentifier: TitleSupplementaryView.reuseIdentifier)
    self.view.addSubview(collectionView)
    collectionView.refreshControl = refreshControl
    self.collectionView = collectionView
}

在上面的代码中,我将集合视图添加到视图控制器视图。

func configureDataSource() {
    guard let collectionView = self.collectionView else {
        return
    }

    dataSource = UICollectionViewDiffableDataSource<String, Int>(collectionView: collectionView) {
        (collectionView: UICollectionView, indexPath: IndexPath, identifier: Int) -> UICollectionViewCell? in

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

        // Populate the cell with our item description.
        cell.label.text = "\(indexPath.section),\(indexPath.item)"

        if self.canLoadNextPage(indexpath: indexPath) {
            self.getNextPage()
        }

        // Return the cell.
        return cell
    }

    dataSource?.supplementaryViewProvider = {
        (collectionView: UICollectionView, kind: String, indexPath: IndexPath) -> UICollectionReusableView? in

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

        headerFooter.label.text = sectionHeader
        headerFooter.backgroundColor = .lightGray
        headerFooter.layer.borderColor = UIColor.black.cgColor
        headerFooter.layer.borderWidth = 1.0

        // Return the view.
        return headerFooter
    }

    var snapshot = NSDiffableDataSourceSnapshot<String, Int>()
    snapshot.appendSections([section])
    items = Array(currentOffset..<currentOffset + 2*itemsPerPage)
    currentOffset += 2*itemsPerPage

    snapshot.appendItems(items)

    serialQueue.async { [weak self] in
        self?.dataSource?.apply(snapshot, animatingDifferences: true)
    }
}

在上面的代码中,我创建了一个构建单元格和标题视图的 diffable 数据源。它还使用初始数据的快照初始化集合视图。快照始终应用在后台串行队列中。

当内容偏移接近尾声时,我将获取下一页数据并应用新快照,如您在此处看到的那样..

func canLoadNextPage(indexpath: IndexPath) -> Bool {
    guard (indexpath.item + 5) > currentOffset else {
        return false
    }

    return true
}

func getNextPage() {
    fetchQueue.asyncAfter(deadline: .now() + 0.5) {
        var snapshot = NSDiffableDataSourceSnapshot<String, Int>()
         snapshot.appendSections([section])
        self.items.append(contentsOf: Array(self.currentOffset..<self.currentOffset + itemsPerPage))
        snapshot.appendItems(self.items)
        self.currentOffset += itemsPerPage

        self.serialQueue.async { [weak self] in
            self?.dataSource?.apply(snapshot, animatingDifferences: true)
        }
    }
}

在此处输入图像描述

Pull To Refresh 操作也观察到类似的行为。

我注意到的另一件事是,当您立即添加数据并在线程之间切换时不会发生这种情况。

感谢任何帮助..

4

0 回答 0