2

I am downloading some images and inserting them into my UICollectionView

These are my class members

var myItems:[UIImage] = []
var myView: UICollectionView?

I have a timer function that receives img:UIImage object. I insert that into my UICollectionView like this

        self.myItems.insert(img, atIndex: self.myItems.count)
        var count:Int? = self.myView?.numberOfItemsInSection(0)
        var index:NSIndexPath = NSIndexPath(forRow: count!, inSection: 0)
        self.myView?.insertItemsAtIndexPaths([index])

I also have this function:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.myItems.count;
}

and this one:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MyCollectionViewCell
    cell.backgroundColor = UIColor.orangeColor()
    cell.textLabel.text = "Text \(indexPath.row)"
    cell.imageView.image = myItems[indexPath.row]
    cell.backgroundView = UIImageView(image: UIImage(named: "cellbg"))
    return cell
}

However my view does not show the new images immediately. I have to tap on the empty screen, then the new cell appears with its image. Also I cannot scroll the view if there are more cells that will fit in the view.

How do I refresh the view? Is there something wrong with the way I am dequeuing the cell?

rosewater
  • 604
  • 2
  • 8
  • 22

2 Answers2

5

You forgot to reload UICollectionView.

self.myView.reloadData()
Nurdin
  • 23,382
  • 43
  • 130
  • 308
2

reloadData did not quite work

then I stumbled on this SO answer

What fixed the problem was calling reloadData from the main thread.

Community
  • 1
  • 1
rosewater
  • 604
  • 2
  • 8
  • 22