Michael Eilers Smith
Michael Eilers Smith

Reputation: 8608

How to update size of cells in UICollectionView after cell data is set?

So I have a UICollectionView with a different image of different size in each cell. When cellForItemAtIndexPath: is called, I update the UICollectionViewCell with a method that fetches an image asynchronously on the web and displays it full size.

My problem is the size of my cell is already set prior with sizeForItemAtIndexPath. I would like it to be recalled so the cell has the downloaded image size.

How can I do this?

Upvotes: 2

Views: 4973

Answers (1)

Logan
Logan

Reputation: 53112

If you have already set up your sizing, find the index of the cell you'd like to refresh:

NSIndexPath * indexPathOfCellToResize = // index path of cell to refresh
[myCollectionView reloadItemsAtIndexPaths:@[indexPathOfCellToResize]];

There's probably a better way to do this, but here's something that works:

Create A Delegate Protocol In Your Cell

@protocol CellDelegate

- (void) imageIsReadyForCell:(id)cell;

@end

Delegate Property

@property (strong, nonatomic) id<CellDelegate>delegate;

In Cell, when image finished call:

[self.delegate imageIsReadyForCell:self];

Then in your file hosting the collectionView in interface

@interface SomeViewController : UIViewController <CellDelegate>

And in the .m

- (void) imageIsReadyForCell:(id)cell {
    NSIndexPath * indexOfReadyCell = [yourCollectionView indexPathForCell:cell];
    [myCollectionView reloadItemsAtIndexPaths:@[indexPathOfReadyCell]];
}

Upvotes: 4

Related Questions