我在视图控制器中有一个水平滚动UICollectionView。每当滚动视图时,视图中的图像都会消失。我试图准备重复使用但没有成功。我已经发布了以下代码:
集合查看单元格
import UIKit
import SDWebImage
class StickerCell: UICollectionViewCell {
@IBOutlet weak var stickerImage: UIImageView!
override func prepareForReuse() {
super.prepareForReuse()
self.stickerImage.image = nil
}
func setImage(image: String) {
let url = NSURL(string: image)
self.stickerImage.contentMode = .ScaleAspectFit
self.stickerImage.clipsToBounds = true
self.stickerImage.center = self.center
self.stickerImage.sd_setImageWithURL(url)
}
}
查看控制器
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.stickers.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: StickerCell = collectionView.dequeueReusableCellWithReuseIdentifier("stickerCell", forIndexPath: indexPath) as! StickerCell
let sticker = stickers[indexPath.row]
if let image = sticker["images"]["medium"].string {
cell.setImage(image)
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath)
if cell?.selected == true {
let sticker = stickers[indexPath.row]
if let image = sticker["images"]["medium"].string {
let url = NSURL(string: image)
self.stickerView.contentMode = .ScaleAspectFit
self.stickerView.clipsToBounds = true
self.stickerView.sd_setImageWithURL(url)
}
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(115, 115)
}
答案 0 :(得分:0)
试试这个.. - >从strickerCell类中删除setImage方法。 - >实现这个
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: StickerCell = collectionView.dequeueReusableCellWithReuseIdentifier("stickerCell", forIndexPath: indexPath) as! StickerCell
let sticker = stickers[indexPath.row]
if let image = sticker["images"]["medium"].string {
let url = NSURL(string: image)
cell.stickerImage.contentMode = .ScaleAspectFit
cell.stickerImage.clipsToBounds = true
cell.stickerImage.sd_setImageWithURL(url, placeholderImage:placeHolderImage, completed: { (image, error, cacheType, url) -> Void in
cell.stickerImage.image = image
})
}
return cell
}
答案 1 :(得分:0)
我用同样的方式绑了这个,但是图像似乎在一段时间内消失了。尝试在Sd_setImage调用上设置一些选项:例如:
self.userProfile.sd_setImage(with: URL(string: self.senderData.userProfileimg), placeholderImage: #imageLiteral(resourceName: "blankProfile"), options: [SDWebImageOptions.progressiveDownload, SDWebImageOptions.continueInBackground], completed: { (image, error, CachedType, url) in
self.userProfile.image = image
})