UICollectionView选中第300个Cell崩溃:无效索引路径异常求助
UICollectionView选中第300个单元格崩溃问题分析与解决方案
我来帮你搞定这个崩溃问题!先看关键报错信息:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 300}'
崩溃核心原因
UICollectionView的单元格索引是从0开始计数的!你有300个单元格,那有效的item索引范围是0到299。而你的代码里直接用EnabledID = 300创建了IndexPath(item: 300, section: 0),这个索引根本不存在,系统自然会抛出越界异常。
从你的代码片段来看,应该是把EnabledID当成了从1开始的序号(比如第1个单元格对应ID1,第300个对应ID300),但转成index path时忘了转换成0-based的下标,这才导致了问题。
具体解决方案
1. 修正索引转换逻辑
读取EnabledID后,先把1-based的编号转换成0-based的索引,再创建index path:
var enabledID = UserDefaults.standard.integer(forKey: "EnabledID") // 处理默认值 if enabledID == 0 { enabledID = 1 UserDefaults.standard.set(1, forKey: "EnabledID") } // 关键:把1-based的ID转成0-based的item索引 let itemIndex = enabledID - 1 // 创建正确的index path并滚动 let indexPath = IndexPath(item: itemIndex, section: 0) yourCollectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
2. 增加安全校验(必加)
为了避免后续数据变化(比如单元格数量减少)再次触发崩溃,建议在滚动前先校验索引的有效性:
let totalItems = yourCollectionView.numberOfItems(inSection: 0) if itemIndex >= 0 && itemIndex < totalItems { let indexPath = IndexPath(item: itemIndex, section: 0) yourCollectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true) } else { // 索引无效时的 fallback 逻辑,比如滚动到第一个单元格 let fallbackIndexPath = IndexPath(item: 0, section: 0) yourCollectionView.scrollToItem(at: fallbackIndexPath, at: .centeredVertically, animated: true) }
3. 统一编号规则(可选优化)
如果你经常遇到这类索引转换错误,可以考虑直接在UserDefaults里存储0-based的下标,这样后续使用时不需要转换,减少出错概率:
// 保存时直接存0-based索引 UserDefaults.standard.set(selectedItemIndex, forKey: "EnabledID") // 读取时直接使用 var enabledIndex = UserDefaults.standard.integer(forKey: "EnabledID") if enabledIndex < 0 || enabledIndex >= yourCollectionView.numberOfItems(inSection: 0) { enabledIndex = 0 UserDefaults.standard.set(0, forKey: "EnabledID") } let indexPath = IndexPath(item: enabledIndex, section: 0) yourCollectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
内容的提问来源于stack exchange,提问作者ameen96mk
相关产品推荐
相关产品推荐

