ios - 将 UIImage 分配给 Collection View 单元格

标签 ios swift uiimage uicollectionview uicollectionviewcell

我在 TableViewController 中有一个 CollectionView。 Collection View 单元格用于显示用户的照片。但是,我从数据库中获取的是 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
  }

到目前为止一切正常。我现在正在成功获取图片网址。

但此时,我对将图像分配给单元格中的 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

}

处理获取图像并将其分配给 Collection View 单元格的 UIImage 的正确方法是什么?

最佳答案

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

collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)

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

关于ios - 将 UIImage 分配给 Collection View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711232/

相关文章:

ios - UIButton 在点击时更改背景(以编程方式)

iOS 电话号码幻灯片菜单

ios - 如何将视网膜捕获的图像绘制回视网膜并保持高质量?

ios - Monotouch Three20 应用程序启动器或绑定(bind)

iphone - 为什么 iOSOpenDev 找不到 LAActivator.h?

ios - 没有半圆的 iPhone 图标

ios - 在 Objective C 中将数字转换为数字

ios - 这个 Xcode 项目文件夹层次结构最可能的设计模式是什么?

ios - 如何从另一个图像的一部分创建图像?

iOS 不保存所有图像