我在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
}
到目前为止,每次都很好。我现在成功获取图像网址。
但是在这一点上,我对将图像分配给单元格中的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的正确方法是什么?
答案 0 :(得分:1)
调用reloadItemAtIndexPaths
的位置取决于您现在如何解决异步操作。应为要下载的每个映像调用异步操作,以便在获取该行的映像时可以更新相应的行。在回调或该操作的任何内容中,您可以调用
collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
然后 myArrayOfIndexPaths
只包含1个项目,它是当前行的indexPath。因此,您将拥有一个异步获取方法,您可以使用当前indexPath作为参数调用该方法。您将其添加到空myArrayOfIndexPaths
,然后调用reload。