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

如何解决UICollectionView中出现的Index out of range致命错误?

解决UICollectionView Index out of range错误的方案

错误根源

  1. 逻辑顺序混乱:不管当前请求的是哪个CollectionView,代码先执行了colView1的cell初始化和imagehome[indexPath.row]的访问。当系统加载colView2的cell时,这行代码依然会被触发,如果colView2的item数量比imagehome数组长度大,直接触发越界。
  2. 数据源与展示数量不匹配:colView1的numberOfItemsInSection返回的数量,大于imagehome数组的元素个数,导致请求的索引超出数组范围。

修复步骤

1. 调整代码逻辑顺序

先判断当前是哪个CollectionView,再分别处理对应的cell和数据源,避免交叉访问错误的数组:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // 优先判断目标CollectionView,避免无效代码执行
    if collectionView == colView2 {
        let cell = colView2.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! CollectionViewCell2
        cell.Image1.image = UIImage(named: imageHome2[indexPath.row])
        cell.Image1.layer.cornerRadius = cell.frame.height/2
        return cell
    } else {
        let cell = colView1.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
        cell.Image.image = UIImage(named: imagehome[indexPath.row])
        return cell
    }
}

2. 确保数据源与展示数量严格匹配

检查numberOfItemsInSection方法,返回对应数据源的元素个数:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == colView2 {
        return imageHome2.count
    } else {
        return imagehome.count
    }
}

3. 增加安全校验(可选但推荐)

数组访问前先判断索引是否合法,避免意外越界:

// 处理colView1时的安全写法
if indexPath.row < imagehome.count {
    cell.Image.image = UIImage(named: imagehome[indexPath.row])
} else {
    // 设置默认图片或空值,避免崩溃
    cell.Image.image = UIImage(named: "default_placeholder")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:01:37