如何在我的UICollectionView上重新加载数据?

时间:2015-05-14 16:22:04

标签: ios swift parse-platform uicollectionview

每次调用UICollectionView时我都需要重新加载我的图像。我目前有两个按钮(还有更多)通过Parse.com查询来切换和填充UICollectionView。当我点击我的按钮时,图像被下载,并且有一个到UICollectionView的segue,但是当我点击" Back"并重新进入UICollectionView。我尝试过使用self.collectionView.reloadData(),但我只收到错误。

var images = [UIImage]()
var imageFiles = [PFFile]()
class CollectionCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

@IBAction func xy1Button(sender: AnyObject) {



}

@IBAction func xy2Button(sender: AnyObject) {
    var downloadImages = PFQuery(className: "XY2")
    downloadImages.whereKey("Expansion", equalTo: "XY2")
    downloadImages.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            println("Successfully retrieved \(objects!.count) images.")
            if let objects = objects as? [PFObject] {
                for object in objects {
                    imageFiles.append(object["Image"] as! PFFile)
                }
            }
        } else {
            println("Error: \(error!) \(error!.userInfo!)")
        }
    }

    self.collectionView.reloadData()
//ERROR IS ABOVE: "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)"

    self.performSegueWithIdentifier("jumpToCollectionView", sender: self)
}

override func viewDidLoad() {



}

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

    return imageFiles.count

}

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

    let cell: CardsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CardsCollectionViewCell
    imageFiles[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData?, error: NSError?) -> Void in

        if error == nil {

            let image = UIImage(data: imageData!)

            cell.Img.image = image
        }
    }
    return cell
}
}

任何帮助?!

2 个答案:

答案 0 :(得分:0)

尝试将self.collectionView.reloadData()包含在异步调度中,如下所示:

dispatch_async(dispatch_get_main_queue(), {
        self.collectionView.reloadData()
    })

我希望我能帮到你!

答案 1 :(得分:-1)

尝试调用self.collectionview.collectionviewlayout.invalidatelayout()以强制更新CollectionView的布局,从而刷新UI。否则,请提供更多信息,因为您的问题不明确。