【问题标题】:Collection view reusing images while scrolling in swift 2在 swift 2 中滚动时重用图像的集合视图
【发布时间】:2015-10-17 06:07:18
【问题描述】:

我简直绝望了,现在搜索了 6 个小时,似乎找不到答案。

我有一个集合视图,其中包含从远程服务器加载的图像,并且在滚动单元格时会用以前的图像刷新几秒钟,然后再稳定下来。 尝试覆盖“准备重用”并将imageview图像设置为nil,但它仍然无法正常工作.. 希望有人能提供一个例子,

非常感谢!

编辑 - 添加代码

集合视图:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath:indexPath) as! PictureCell

    cell.pictureCD = GalleryCD().fetchTable()[indexPath.row]

    return cell
}

CollectionViewCell:

class PictureCell: UICollectionViewCell {
@IBOutlet weak var picture: UIImageView!

var pictureCD: NSManagedObject! {
    didSet { self.setupData() }
}

override func prepareForReuse() {
    super.prepareForReuse()

    self.picture.image = nil
    self.picture.setNeedsDisplay() // tried adding after some recommendations
    self.setNeedsDisplay()         // tried adding after some recommendations
}

func setupData(){
    self.picture.image = UIImage(named: "blank")

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        let URL = (NSURL (string: url.pictureSquareGET(picture: self.pictureCD)))!

        let data = NSData(contentsOfURL: URL)!

        dispatch_async(dispatch_get_main_queue()) {
            self.picture.image = UIImage(data: data)
        }
    })
}

}

【问题讨论】:

  • 您是否调用了 super.prepareForReuse 作为 prepareForReuse 中的第一条语句?
  • 粘贴上面的代码,谢谢
  • @John 你能找到解决方案吗?如果您找到解决方案,请建议我修复我也面临同样的问题。谢谢

标签: ios xcode swift uicollectionview uicollectionviewcell


【解决方案1】:

你可以更新 prepareForReuse 方法

override func prepareForReuse() {

    myImageView.image = nil

    super.prepareForReuse()
}

【讨论】:

    【解决方案2】:

    由于单元格重复使用,您的单元格中加载了以前的图像,因此您是正确的。

    您需要做的就是在您的 cellForItemAtIndexPath 中将单元格图像设置为 nil,然后再从您的服务器获取更新的图像。

    【讨论】:

    • 这是显而易见的解决方案,但 prepareForReuse 应该已经将图像设置为 nil。
    • 你介意看看我做错了什么吗?
    • 你还遇到同样的问题吗?
    • @Dima 如果您的解决方案正常工作,您能否上传您的解决方案?我正在努力解决类似的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多