Dynamically change cell size according to image in a UICollectionView

后端 未结 2 1855
孤独总比滥情好
孤独总比滥情好 2021-02-15 12:04

I am displaying dynamic images recieved from server in a horizontal collection view. When I set up the collectionview I set this:

-(void)setupCollectionView{
[se         


        
相关标签:
2条回答
  • 2021-02-15 12:42

    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);
    }
    
    0 讨论(0)
  • 2021-02-15 12:44

    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.

    0 讨论(0)
提交回复
热议问题