Resizing UICollectionViewCell After Data Is Loaded Using invalidateLayout

回眸只為那壹抹淺笑 提交于 2019-12-03 12:46:19

Actually, from what I found, calling to invalidateLayout will cause calling sizeForItemAtIndexPath for all cells when dequeuing next cell (this is for iOS < 8.0, since 8.0 it will recalculate layout in next view layout update).

So the solution i came up with, is subclassing UICollectionView, and overriding layoutSubviews with something like this:

- (void)layoutSubviews
{
    if ( self.shouldInvalidateCollectionViewLayout ) {
        [self.collectionViewLayout invalidateLayout];
        self.shouldInvalidateCollectionViewLayout = NO;
    } else {
        [super layoutSubviews];        
    }
}

and then calling setNeedsLayout in cellForItemAtIndexPath and setting shouldInvalidateCollectionViewLayout to YES. This worked for me in iOS >= 7.0. I also implemented estimated items size this way. Thx.

Here my case and solution.

My collectionView is in a scrollView and I want my collectionView and her cells to resize as I'm scrolling my scrollView.

So in my UIScrollView delegate method : scrollViewDidScroll :

[super scrollViewDidScroll:scrollView];

if(scrollView.contentOffset.y>0){

    CGRect lc_frame = picturesCollectionView.frame;
    lc_frame.origin.y=scrollView.contentOffset.y/2;
    picturesCollectionView.frame = lc_frame;
}
else{

    CGRect lc_frame = picturesCollectionView.frame;
    lc_frame.origin.y=scrollView.contentOffset.y;
    lc_frame.size.height=(3*(contentScrollView.frame.size.width/4))-scrollView.contentOffset.y;
    picturesCollectionView.frame = lc_frame;

    picturesCollectionViewFlowLayout.itemSize = CGSizeMake(picturesCollectionView.frame.size.width, picturesCollectionView.frame.size.height);
    [picturesCollectionViewFlowLayout invalidateLayout];
}

I had to re set the collectionViewFlowLayout cell size then invalidate his layout. Hope it helps !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!