您好,我的 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/