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

