You need to enable JavaScript to run this app. 如何使用UICollectionViewDiffableDataSource实现快速滚动索引条
优惠活动
大模型
产品
解决方案
定价
更多

如何使用UICollectionViewDiffableDataSource实现快速滚动索引条

使用UICollectionViewDiffableDataSource实现集合视图滚动索引(Scrubber)方案

核心实现思路

iOS 15 及更低版本中UICollectionViewDiffableDataSource未原生提供索引标题相关的配置入口,我们可以通过子类化UICollectionViewDiffableDataSource,新增索引相关的自定义闭包属性,并重写对应的数据源方法实现该功能。

步骤1:自定义支持索引的差异化数据源子类

class IndexedDiffableDataSource<Section: Hashable, Item: Hashable>: UICollectionViewDiffableDataSource<Section, Item> {
    /// 提供索引标题数组的闭包,调用时机对应原数据源的indexTitlesForCollectionView方法
    var indexTitlesProvider: ((UICollectionView) -> [String]?)?
    /// 匹配索引标题对应位置的闭包,调用时机对应原数据源的indexPathForIndexTitle方法
    var indexPathForIndexTitleProvider: ((UICollectionView, String, Int) -> IndexPath?)?

    override func indexTitles(for collectionView: UICollectionView) -> [String]? {
        indexTitlesProvider?(collectionView)
    }

    override func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
        indexPathForIndexTitleProvider?(collectionView, title, index) ?? IndexPath(item: 0, section: 0)
    }
}

步骤2:使用自定义子类完成索引配置

初始化数据源时替换原UICollectionViewDiffableDataSource为自定义子类,配置索引相关闭包即可:

// 初始化自定义数据源,原有Cell配置逻辑无需改动
let dataSource = IndexedDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, item in
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellID", for: indexPath)
    // 原有Cell内容配置逻辑
    return cell
}

// 配置索引标题列表
dataSource.indexTitlesProvider = { [weak self] _ in
    // 此处返回当前数据源对应的索引数组,比如按首字母分组的["A","B","C"...]
    return self?.currentIndexTitles ?? []
}

// 配置索引点击跳转逻辑
dataSource.indexPathForIndexTitleProvider = { [weak self] _, title, index in
    guard let self = self else { return IndexPath(item: 0, section: 0) }
    // 根据点击的索引标题匹配对应Section的位置,返回对应Section首行的IndexPath即可
    let targetSection = self.sectionList.firstIndex { $0.indexTitle == title } ?? 0
    return IndexPath(item: 0, section: targetSection)
}

注意事项

  • iOS 16 及以上系统已原生支持UICollectionViewDiffableDataSource的索引配置,可直接使用官方提供的sectionIndexTitlesProvider、sectionIndexTitleSnapshot等API,无需自定义子类。
  • 索引标题数组需要和当前生效的snapshot数据保持同步,避免出现索引跳转错位的问题。
  • 该方案完全兼容原有差异化数据源的增量更新能力,不会影响原有页面的刷新逻辑。

内容的提问来源于stack exchange,提问作者Tom Hamming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:54:03