0
votes

I created a custom UIViewController and extended it to implement: UICollectionViewDataSource, UICollectionViewDelegate. In story board, I added UICollectionView and made reference from my controller to this UICollectionView (and setup the delegates for data source and collection view delegate).

I obviously implemented the minimal requirements for these 2 delegates. Now, since i sometimes asynchronously load images, I call cell.setNeedsLayout(), cell.layoutIfNeeded(), cell.setNeedsDisplay() methods after image download done (cell.imageView.image = UIImage(...)). I know all these methods are called. However, the images on the screen were not updated.

Did I miss something? Thank you!

Edit: Add Sample code - how update was called -

    func collectionView(collectionView: UICollectionView,
    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
    ....

    let cellImage = ServiceFacade.sharedInstance.getImageFromCaching(image!.url)
    if cellImage == nil {
        // set image to default image.
        cell.cellImage.image = UIImage(named: "dummy")

        ServiceFacade.sharedInstance.getImage(image!.url, completion: { (dImage, dError) in
            if dError != nil {
               ...
            }
            else if dImage != nil {
                dispatch_async(dispatch_get_main_queue(),{


                    let thisCell = self.collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
                    thisCell.cellImage.image = dImage
                    thisCell.setNeedsLayout()
                    thisCell.setNeedsDisplay()
                    thisCell.layoutIfNeeded()
                })

            }
            else{
                // do nothing
            }
        })
    }
    else {
        cell.cellImage.image = cellImage!
        cell.setNeedsDisplay()
    }

    // Configure the cell
    return cell

}
1
Are you setting the image after download on the main thread? The cell might be nil when download is complete. If you can post some of the code when you download and set the imageYan
Yan, thanks for looking into it for me. Here is the code that I used to call the cell update. But it did not work.BSharer App - Share Books

1 Answers

0
votes

Chances are the UICollectionView has cached an intermediate representation of your cell so that it can scroll quickly.

The routine you should be calling to indicate that your cell needs to be updated, resized, and have it's visual representation redone is reloadItemsAtIndexPaths with a single index path representing your cell.