我尝试使用存储在Parse.com帐户中的图像填充CollectionView。我写了一个简单的查询来获取这些图像并将它们存储在一个数组中。我只是不知道如何将这些图像放入细胞中。
class AvatarCollectionViewController: UICollectionViewController {
var avatars: [PFObject] = []
var user: PFUser!
var imageFile: PFFile
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Get the avatars from Parse
let avatarQuery = PFQuery(className: "Avatar")
avatarQuery.findObjectsInBackgroundWithBlock{
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects {
for object in objects {
self.avatars.append(object)
self.imageFile = object["file"] as! PFFile
}
}
}
}
}
再往下我有处理细胞的功能。我知道我已经接近但我无法获得要显示的图像:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AvatarViewCell
let userImageFile = self.avatars[indexPath.row]["file"]
print(userImageFile)
userImageFile?.getDataInBackgroundWithBlock{
(imageData: NSData?, error: NSError?) -> Void in
if error == nil{
let image = UIImage(data: imageData!)
cell.imageCell.image = image
} else {
print(error)
}
}
//cell.imageCell.image = UIImage(named: self.avatars[indexPath.row]["file"] as! String)
return cell
}
整个视图是黑色的,没有错误。任何帮助表示赞赏。感谢
编辑:更新了cellForItemAtIndexPath函数。即使cell.imageCell.image = image
将值输出到控制台,print(userImageFile)
处的Nil错误也会崩溃。