Question

I am working on implementing a UICollectionView that gets its data from online via Parse. I am loading images into the collection view. The problem that I'm having is that one of the delegate methods for the collection view gets called before the cells have been reloaded.

I have a method that loads the objects in the background into an NSArray. Once they are all done I reload my collection view. From there my delegate method is being called prior to collectionView:cellForItemAtIndexPath. My delegate method handles the size of each individual cell so that they can change based on the size of a photo.

That's a problem because the cells need to have images in them in order for me to see what size they are for the delegate method.

My delegate method looks like this:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(NHBalancedFlowLayout *)collectionViewLayout preferredSizeForItemAtIndexPath:(NSIndexPath *)indexPath
{   
    CustomCollectionViewCell *currentCell = (CustomCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    if (currentCell) {
        return [currentCell.cellImage.image size];
    }
    return [cellImage size];
}

Like I said, This delegate method is being called before collectionView:cellForItemAtIndexPath. That is resulting in the local variable 'currentCell' return nil. What could I do so that I can properly set this up so after all of my cells are loaded I call the delegate?

Was it helpful?

Solution

I was having this same probably with the Parse table view. You're absolutely right about how parse collection and table views set their dimensions. The problem can be solved by saving the width and height of the image when you upload it. This way, you can just grab the dimensions of the image before the PFFile image has finished downloading (this usually happens after the collection view is set up).

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyParseImage *image = [self.objects objectAtIndex:indexPath.row];
    CGFloat imageHeight = [[image objectForKey:height] floatValue];
    CGFloat imageWidth = [[image objectForKey:width] floatValue];
    CGFloat ratio = self.view.frame.size.width / imageWidth;

    return imageHeight * ratio;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top