You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击CollectionView单元格时,如何让UITableView滚动到最后一个分区头部?

解决UITableView点击CollectionView后无法滚动到最后一个分区头部的问题

你的问题出在使用scrollToRow(at:at:animated:)方法,它是将指定行的顶部对齐到TableView的顶部,但最后一个分区的头部位于该行上方,当TableView剩余空间不足以让header完全滚动到顶部时,就会出现无法显示在最顶端的情况。直接滚动到分区头部的矩形区域就能解决这个问题。

修改后的核心代码

替换UICollectionViewDelegate中的didSelectItemAt方法:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let targetSection = indexPath.row
    // 获取目标分区头部的Frame
    guard let headerRect = tableView.rectForHeader(inSection: targetSection) else { return }
    // 滚动到头部区域,确保头部对齐到顶部
    tableView.scrollRectToVisible(headerRect, animated: true)
}

额外优化点

你原来的代码中通过filter和firstIndex获取分区索引的逻辑完全多余,因为CollectionView的indexPath.row直接对应TableView的分区索引,直接使用即可,省去不必要的数组遍历操作。

完整修改后的CollectionView代理扩展

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mobileBrand.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TopSectionCVC", for: indexPath) as! TopSectionCVC
        cell.lblTopSection?.text = mobileBrand[indexPath.row].brandName
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let targetSection = indexPath.row
        guard let headerRect = tableView.rectForHeader(inSection: targetSection) else { return }
        tableView.scrollRectToVisible(headerRect, animated: true)
    }
}

内容的提问来源于stack exchange,提问作者Nilay M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:19:52