Swift CollectionView 随机图像为 null

标签 swift uicollectionview uicollectionviewcell

您好,我的 UICollectionView 有问题。首先,我有一个来自服务器的图像列表,其中包含 url 图像。

但是当 url 为 null 时,单元格显示随机图像。我想要当 url 为 null 时,只是不显示图像。

我正在使用 SDWebImage 向 UIImageView 显示图像。

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return listData.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! MyCollectionListViewCell
        if let url = self.listData[indexPath.row]["photo"] as? String {
            let urlPhoto = NSURL(string:url!)
            cell.imageView.sd_setImageWithURL(urlPhoto, placeholderImage:img)
            cell.imageView.contentMode = UIViewContentMode.ScaleAspectFill
            cell.imageView.layer.masksToBounds = true
            cell.imageView.clipsToBounds = true
         }
}

最佳答案

由于 UICollectionViewCell 将被重用,只需将单元格的图像设置为 nil:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! MyCollectionListViewCell
        if let url = self.listData[indexPath.row]["photo"] as? String {
            let urlPhoto = NSURL(string:url!)
            cell.imageView.sd_setImageWithURL(urlPhoto, placeholderImage:img)
            cell.imageView.contentMode = UIViewContentMode.ScaleAspectFill
            cell.imageView.layer.masksToBounds = true
            cell.imageView.clipsToBounds = true
         } else {
            cell.imageView.image = nil
         }
}

关于Swift CollectionView 随机图像为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42574988/

相关文章:

ios - 没有互联网连接的位置

ios - UICollectionView 边界宽度始终为 600

ios - 在uicollectionview(单选)中设置对所选单元格的影响ios swift

ios - 为什么我不能将 UICollectionViewFlowLayout 中的 referenceSizeForFooterInSection 与 EstimateItemSize 一起使用?

ios - 在swift中过滤字典

swift - 从 AVCaptureSession 录制的音频在流式传输到另一台设备时生成 "Bad Address"错误

ios - 在每行 3 个单元格布局中将 cornerRadius 添加到第一个和第三个 UICollectionViewCell

ios - UICollectionView 中的最后一个单元格被剪裁

ios - 为 collectionView 中的每个其他项目设置特定布局

arrays - 在包含自定义类的数组中查找值