Swift 4:集合视图“cellForItemAt”索引超出范围

问题描述 投票:0回答:3

我收到索引超出范围致命错误。我正在尝试在表视图控制器的一个单元格中实现 2 个集合视图。两者都有不同的数据源。从数据源加载单元格中的图像数据时,由于此错误,第二个集合视图单元格未加载图像数据。 即使我转储

BList
的内容,它也有 5 个以(键,值)对方式存在的对象 错误发生在以下行

let bannerList = BList[indexPath.row]

我看过其他类似的问题,但没有一个有用

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! T_PCollectionViewCell

    if (collectionView === upperBannerCollectionView) {
        if OList.count > 0 {
            let olist2 = OList[indexPath.row]
            cell.load_image(olist2.banner_image)
        }
    } else {
        if BList.count > 0 {
            let blist = BList[indexPath.row]
            cell.load_image(blist.banner_image)
        }
    }
    return cell
}

这是 collectionView 的 `numberOfItems' 的实现

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        if (collectionView === uBCollectionView) {
            return self.OList.count
        } else {
            return self.BList.count
        }
    }

增加了带图像打印(BList)的调试

debug of print(BList) debugger screenshot

在尝试从数据源 BannerList 加载数据时,我不应该出现此类索引超出范围错误。

ios swift uicollectionview
3个回答
0
投票

首先,我认为你的主要问题是“numberOfItemsInSection”中的数组。

假设您在“numberOfItemsInSection”中使用OtokuList.count OtokuList 此时有 3 个项目,但 BannerList 只有一个项目。

 if BannerList.count > 0 { //this validation will work even if indexPath.row is 2
       let bannerList = BannerList[indexPath.row] //this line will crash
       cell.load_image(bannerList.banner_image)
  }

我的解决方案是:

if BannerList.count > indexPath.row {
      let bannerList = BannerList[indexPath.row]
      cell.load_image(bannerList.banner_image)
}

0
投票

我认为当collectionView无法找到索引时这个问题是准确的。为了解决这个问题,我们需要应用小额支票。 yourArray.count > indexPath.row。

 if cellData.viewModel.serviceCategoriesArray.count > indexPath.row {
        
        cellData.viewModel.selectedCategory = cellData.viewModel.serviceCategoriesArray[indexPath.row]
    }

0
投票

我也有类似的问题。就我而言,发生这种情况是因为 viewDidLoad 中正在重新加载数据。当我将重新加载更改为 viewWillAppear 时,集合视图以正确的 indexPath.row 开始。

© www.soinside.com 2019 - 2024. All rights reserved.