Dynamically change cell size according to image in a UICollectionView

白昼怎懂夜的黑 提交于 2019-12-03 12:53:57

In -setImageWithURLRequest:..., when the image loads cache it in a hash table, and then call -reloadItemsAtIndexPaths: with the current image path, to reload the cell and thus causing the CollectionView to re-check what size the cell should be.

Make sure you consult the hash table when looking up the image. This will also save you extra network accesses in cases where the collectionView items scroll offscreen and back on again.

Note I am worried that if you’re using a UICollectionReusableView subclass your code can fail, because cells can be re-used before their images ever load, so the images will load in the wrong place.

However add an delegate method of UICollectionView.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[arryOfImg objectAtIndex:indexPath.row]]];

    //You may want to create a divider to scale the size by the way..
    return CGSizeMake((image.frame.size.width)/4.0, (image.frame.size.height)/4.0);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!