我正在努力处理这段代码。
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.count
和 indexPath.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/