Swift CollectionView 为空时的随机图像

Swift CollectionView random image when null

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

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

我正在使用 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
         }
}

您也可以将此方法添加到您的单元格中 class :

    override func prepareForReuse() {
    self.imageView.image = nil
    super.prepareForReuse()
}