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

如何用IGListKit实现UICollectionViewCell选中动画?遇section索引获取难题

解决IGListKit中SectionController获取对应Section索引的问题

嘿,你的思路本身没问题——用didHighlightItem和didUnhighlightItem实现UICollectionViewCell的点击高亮动画是很常规的做法,问题出在IGListKit的架构设计上:它的ListSectionController和原生UICollectionView的section是解耦的,所以没法直接从单元格拿到section编号,得用IGListKit提供的映射方法来获取。

获取SectionController对应的原生Section索引

IGListKit的ListAdapter提供了专门的方法来获取某个SectionController对应的UICollectionView section位置,你可以在PersonSectionController里这样用:

override func didHighlightItem(at index: Int) {
    // 先拿到当前要高亮的单元格
    guard let cell = collectionContext?.cellForItem(at: index, sectionController: self) as? PersonCell else { return }
    
    // 通过listAdapter获取当前SectionController对应的section索引
    if let sectionIndex = listAdapter?.section(for: self) {
        // 这里就拿到了你需要的section编号,可以结合它做差异化动画
        print("高亮单元格所在Section: \(sectionIndex),Item位置: \(index)")
        
        // 执行你的高亮动画,比如缩放
        UIView.animate(withDuration: 0.2) {
            cell.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
        }
    }
}

override func didUnhighlightItem(at index: Int) {
    guard let cell = collectionContext?.cellForItem(at: index, sectionController: self) as? PersonCell else { return }
    
    if let sectionIndex = listAdapter?.section(for: self) {
        print("取消高亮单元格所在Section: \(sectionIndex),Item位置: \(index)")
        
        // 恢复单元格状态
        UIView.animate(withDuration: 0.2) {
            cell.transform = .identity
        }
    }
}

额外注意点

  • 确保你的PersonSectionController已经被正确添加到ListAdapter中,否则listAdapter属性会是nil,拿不到section索引。你可以在didUpdate(to object: Any)方法里确认一下关联状态,或者在初始化时做必要的绑定。
  • 如果你的动画逻辑不依赖section编号,其实可以直接操作单元格,不需要获取section——但如果是要根据不同section做不同动画,上面的方法就完全适用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:40:35