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

ryoqjall  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(87)
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
}

如何解决此错误?

daupos2t

daupos2t1#

重写代码以获取不同的图像,具体取决于您为哪个集合视图提供单元格:

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。那没用的

相关问题