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
  • 530
  • 2
  • 6
  • 18

3 Answers3

4

You forgot to reload UICollectionView.

self.myView.reloadData()
Mohammad Nurdin
  • 20,761
  • 38
  • 117
  • 280
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
  • 530
  • 2
  • 6
  • 18
-1

Swift 4 Dispatch the collection.reloadData() to the main queue from inside the cellForItemAt and it will worke like a charm

var cellsCount = 0
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = campaignsCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell

cell.updateCell()

    // TO UPDATE CELLVIEWS ACCORDINGLY WHEN DATA CHANGES
    // AND THE 'IF CONDITION' is TO AVOID PERFORMANCE LEAK
    if cellsCount <= itemsArray.count {
        DispatchQueue.main.async {
            self.campaignsCollection.reloadData()
        }
        cellsCount += 1
    }

    return cell
}
Wissa
  • 871
  • 14
  • 21