将 UIImage 分配给集合视图单元格

Assigning UIImage to Collection View Cell

我在 TableViewController 中有一个 CollectionView。集合视图单元格用于显示用户的照片。但是,我从数据库中获取的是 url 路径。

我还打算对图像数据进行更多操作,因此我选择将它们存储在数组中profileImages(但我不确定是否应该使用 NSURL 数组)..

(我也使用 Firebase 作为后端,它会实时监听变化,这就是我设置 isIndexValid 检查部分的原因)

class TableViewController: UITableViewController, UICollectionViewDataSource {

   @IBOutlet weak var collectionView: UICollectionView!

   var profileImages = [NSURL]()

   // Database Checks Hits into `retrievePhotos()`

   func retrieveUserPhotos(user: AnyObject) {
    if let profilePicLink = user["firstImage"]! {
        let firstImagePath = profilePicLink as! String

        if let fileUrl = NSURL(string: firstImagePath) {
            print(fileUrl)
            let isIndexValid = profileImages.indices.contains(0)

            if (!isIndexValid) {
                profileImages.append(fileUrl)
                print(profileImages)
            } else {
                profileImages[0] = fileUrl
            }
        }
     }
   }

  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
  }

到目前为止一切正常。我现在正在成功获取图像 url。

但在这一点上,我对将图像分配给单元格中的 UIImage 感到困惑。 (我尝试将它与 Heneke 一起使用,因为它似乎更容易)。

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = self.collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell

    // below returns fatal error `Index out of range`
    cell.currentImage.hnk_setImageFromURL(profileImages[indexPath.row])


    // Also tried this but it doesn't update the UIImage. 
   // I guess it's because it's already loaded once without download of the images from the link get completed:
    if profileImages.count > 0 {
      cell.currentImage.hnk_setImageFromURL(profileImages[indexPath.row])
    }

    return cell

}

处理获取图像并分配给集合视图单元格的 UIImage 的正确方法是什么?

在哪里调用 reloadItemAtIndexPaths 取决于您现在如何解决异步操作。应该为您正在下载的每个图像调用您的异步操作,以便您可以在获取该行的图像时更新相应的行。在回调或该操作的任何内容中,您调用

collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)

myArrayOfIndexPaths 将只包含 1 个项目,即当前行的 indexPath。因此,您将拥有一个使用当前 indexPath 作为参数调用的异步获取方法。您将其添加到一个空 myArrayOfIndexPaths,然后调用 reload。