点击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
相关产品推荐
相关产品推荐

