致命错误:索引超出范围 。靠近评论

Fatal error: Index out of range . Coming near the comment

提问人:Harsh Soni 提问时间:9/28/2023 最后编辑:HangarRashHarsh Soni 更新时间:9/28/2023 访问量:34

问:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=colView1.dequeueReusableCell(withReuseIdentifier:"cell",for: indexPath) as! MyCollectionViewCell
    cell.Image.image=UIImage (named: imagehome[indexPath.row])           //error
    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
    }
    return cell
}

如何解决此错误?

iOS Swift UIColictionView

评论

0赞 Larme 9/28/2023
numberOfSection 和 numberOfRows 的代码是什么?
0赞 Larme 9/28/2023
您应该在之前检查: 因为您每次都输入特定代码,如果还有更多代码,则会出现错误......if collectionView == colView1 { ... } else if collectionView = colView2 { ... }colView2imageHome2imagehome
0赞 Duncan C 9/28/2023
您需要发布 和 方法的代码。您还需要将分配单元格图像的代码移动到 if 语句中,这样您就不会尝试从模型中获取错误表视图的图像。(如果 imageHome2 包含的图像多于 imageHome,则代码将崩溃,因为它将尝试从错误的数组中获取图像。tableView(_:numberOfRowsInSection:)numberOfSections(in:)imagehome[indexPath.row]
0赞 Duncan C 9/28/2023
我建议不要编写处理 2 个不同表视图的数据源的代码。这只会让你感到困惑。设置两个不同的对象,为不同的表视图提供数据。
0赞 Duncan C 9/28/2023
对不起,我上面的评论应该说“集合视图”,而不是表格视图。如果使用适当的集合视图数据源方法,则注释仍然适用。

答:

0赞 Duncan C 9/28/2023 #1

重写代码以根据要为其提供单元格的集合视图获取不同的图像:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // Change the line below to dequeue a cell from the collection view passed to the function. 
    //(Make sure you have a cell with the identifier "cell" defined for both collection views.)
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"cell",for: indexPath) as! MyCollectionViewCell
    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 {
        // I moved this line into an else block for the other collection view (colView1?)
        cell.Image.image=UIImage (named: imagehome[indexPath.row])   
        // Do the other setup for a cell from colView1 here.        

    return cell
}

您的代码还尝试从 colView1 中取消单元格的队列,即使请求来自 colView2。那行不通。