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

UITableViewCell嵌套UICollectionView报Index out of range错误原因排查

解决UICollectionView Index Out of Range错误

嘿,这个错误的根源太明显啦——你在cellForItemAt里错误地把collectionView.tag同时用来索引两个完全不同的数组!

问题拆解

你设置collectionView.tag的目的应该是标记当前对应的Venue在数组中的位置(也就是tableView的行号),所以filteredVenueArray[collectionView.tag]是没问题的。但你紧接着又用同一个tag去取imgURLs的元素,这就大错特错了:

  • 每个Venue的imgURLs只有2个元素,索引范围是0和1
  • 当你的tableView滚动到第3行(tag=2)、第4行(tag=3)时,去取imgURLs[2]或者imgURLs[3],自然就触发Index out of range错误了!

修复后的完整代码

你需要用UICollectionView自身的indexPath.item来获取当前图片在imgURLs中的索引,这才是正确的打开方式:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VenueListingCellImage", for: indexPath) as! VenueListingCellImage
    
    // 1. 先通过tag拿到当前对应的Venue对象
    let currentVenue = filteredVenueArray[collectionView.tag]
    // 2. 用collectionView的indexPath.item取对应位置的图片URL
    let urlString = currentVenue.imgURLs[indexPath.item]
    
    // 额外优化:别用强制解包!用可选绑定避免URL初始化失败崩溃
    if let imgURL = URL(string: urlString) {
        cell.configureCell(url: imgURL)
    } else {
        // 这里可以设置一张默认图片,或者做错误提示
        cell.configureCell(url: nil)
    }
    
    return cell
}

额外注意事项

请确保你在tableView的cellForRowAt方法里,正确给每个cell内的collectionView设置了tag:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withReuseIdentifier: "YourTableViewCellID", for: indexPath) as! YourTableViewCell
    
    // 关键:把tag设置为当前tableView的行号,对应Venue在数组中的索引
    cell.collectionView.tag = indexPath.row
    cell.collectionView.reloadData()
    
    return cell
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:49:55