Swift 2:UICollectionView - 是否可以异步返回单元格?

时间:2015-12-23 03:08:54

标签: swift asynchronous parse-platform uiimage uicollectionview

我在UIView容器中有一个UICollectionView,我用它来显示附加到存储在 Parse中的PFFile的图像(作为PFObject数组} 。我知道我可以在当前的实现中同步获取PFFile / image(参见下面的同步加载工作代码),但我真的想让它成为一个异步过程。

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

        if let uploadImageFile = attachedImageFiles[indexPath.row] as? PFFile {



            do {
                var imageData: NSData
                try imageData = uploadImageFile.getData()
                cell.imageView.image = UIImage(data: imageData)
            } catch let err as NSError {
                print("error getting image file data: \(err)")
            }

            /*
            //asynchronously getting image data - don't know how to return cell here
            uploadImageFile.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
                if error != nil {
                    //TODO: show error in download
                }
                if imageData != nil {
                    cell.imageView.image = UIImage(data: imageData!)
                }
            })
            */
        }

      return cell
    }

我一直在考虑的一种方法是让AttachedImageCollectionViewCell对象观察其UIImageView,一旦为其分配了UIImage文件(指针),它就会获取PFFile从Parse解析并解析为NSData,用于UIImage。

由于我仍处于掌握Swift的学习曲线上,我不确定这种方法的可行性。 所以我在这里听到任何想法,谢谢!

1 个答案:

答案 0 :(得分:1)

因此,在创建单元格的代码中,您可以确保使用库将图像异步设置为单元格 -

https://github.com/natelyman/SwiftImageLoader/blob/master/ImageLoader.swift

//Create cell in usual way
//Code here to create the cell 

//Load the image needed by the cell asynchronously
ImageLoader.sharedLoader.imageForUrl(urlString, completionHandler:{(image: UIImage?, url: String) in
    cell.image = image
}) 

HTH