swift - IndexArray 超出范围,具有默认的 collectionviewcells 数量

标签 swift uicollectionviewcell

我正在努力处理这段代码。

if facebookPhotos.count != 0 {         
    if let data = NSData(contentsOfURL: facebookPhotos[indexPath.row]) {    
        let image = UIImage(data: data)
        collectionCell.collectionViewImage.image = image
    }
}

我有一个 facebookphotos 数组和一个 UICollectionView => 默认返回 6 个单元格。

当我尝试将照片加载到其中时(比方说 3),它崩溃了。我怎样才能让 6 个单元格出现,但只有那些填充的单元格,它们在 indexPath.row 有一个等效的照片?

不过,拥有这 6 个 Cell 很重要。

最佳答案

避免索引数组超出范围异常很简单:您需要做的就是比较 facebookPhotos.countindexPath.row:

if facebookPhotos.count < indexPath.row {         
    if let data = NSData(contentsOfURL: facebookPhotos[indexPath.row]) {    
        let image = UIImage(data: data)
        collectionCell.collectionViewImage.image = image
    }
} else {
    // Clear out the image on a recycled cell
    collectionCell.collectionViewImage = nil
}

关于swift - IndexArray 超出范围,具有默认的 collectionviewcells 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34414339/

相关文章:

swift - 堆叠式进度指示器 swift

ios - AVSpeechSynthesizer 不适用于 iOS10

ios - swift - UICollectionView 或 UIImage - 如何防止图像缓存

swift - 创建 FCM 设备组返回 401

objective-c - 有没有办法知道哪个 Collection View 单元格在特定点?

ios - 为什么我的 tableView 没有被填充?

objective-c - 删除编辑按钮上的 UICollectionView 单元格

ios - AFNetworking 2.0 和下载多张图片

ios - 如何使两个 Collection View 出现在同一个 View Controller 上?

ios - 在 UICollectionView 上禁用单元格重用