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

iOS 18中检查cellForItemAt后调用scrollToItem导致崩溃求助

问题分析与解决方案

崩溃原因

你这段代码的问题出在错误使用cellForItemAt来判断数据源是否存在对应位置的单元格。collectionView(_:cellForItemAt:)是UICollectionViewDataSource协议中用于提供单元格实例的方法,它的设计目的不是用来验证某个IndexPath是否有效——iOS 18之前的系统可能只是返回nil,但iOS 18对这种非法调用做了更严格的校验,直接触发崩溃。

修复后的代码

正确的做法是通过数据源的collectionView(_:numberOfItemsInSection:)方法来验证目标section是否存在,且该section下有至少一个item:

extension UICollectionView {
    func scrollToFirst(inSection: Int = 0, animated: Bool = false) {
        // 先判断section是否在合法范围内
        guard inSection >= 0, inSection < numberOfSections else {
            return
        }
        // 再判断该section下是否有至少一个item
        let itemCount = dataSource?.collectionView(self, numberOfItemsInSection: inSection) ?? 0
        guard itemCount > 0 else {
            return
        }
        // 安全滚动到目标位置
        scrollToItem(at: IndexPath(row: 0, section: inSection), at: .right, animated: animated)
    }
}

额外说明

  • 优先使用numberOfSections判断section合法性,避免传入负数或超出范围的section索引
  • 通过numberOfItemsInSection:获取对应section的item数量,这才是验证IndexPath是否有效的标准方式
  • 保留了原方法的默认参数,确保调用方式无需修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:22:05