【发布时间】:2016-04-19 07:20:07
【问题描述】:
我在 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 的正确方法是什么?
【问题讨论】:
-
我更新了我的问题。如果我签入
cellForItemAtIndexPath,图像永远不会更新 -
后来的答案是
collectionView.reloadData().. 稍作调整后,我明白了它的本质。谢谢 -
您应该查看 reloadRowsAtIndexPaths 而不是 reloadData()。您不想在每次异步操作完成时重新加载整个视图
-
@Moonwalkr 你能否举一个例子来回答如何实现它?我可以接受你的回答。 collectionView 有
reloadRowsAtIndexPaths吗?
标签: ios swift uiimage uicollectionview uicollectionviewcell