Dynamically setting layout on UICollectionView causes inexplicable contentOffset change

前端 未结 10 1639
一生所求
一生所求 2020-11-29 16:10

According to Apple\'s documentation (and touted at WWDC 2012), it is possible to set the layout on UICollectionView dynamically and even animate the changes:

10条回答
  •  孤城傲影
    2020-11-29 16:46

    I have been pulling my hair out over this for days and have found a solution for my situation that may help. In my case I have a collapsing photo layout like in the photos app on the ipad. It shows albums with the photos on top of each other and when you tap an album it expands the photos. So what I have is two separate UICollectionViewLayouts and am toggling between them with [self.collectionView setCollectionViewLayout:myLayout animated:YES] I was having your exact problem with the cells jumping before animation and realized it was the contentOffset. I tried everything with the contentOffset but it still jumped during animation. tyler's solution above worked but it was still messing with the animation.

    Then I noticed that it happens only when there were a few albums on the screen, not enough to fill the screen. My layout overrides -(CGSize)collectionViewContentSize as recommended. When there are only a few albums the collection view content size is less than the views content size. That's causing the jump when I toggle between the collection layouts.

    So I set a property on my layouts called minHeight and set it to the collection views parent's height. Then I check the height before I return in -(CGSize)collectionViewContentSize I ensure the height is >= the minimum height.

    Not a true solution but it's working fine now. I would try setting the contentSize of your collection view to be at least the length of it's containing view.

    edit: Manicaesar added an easy workaround if you inherit from UICollectionViewFlowLayout:

    -(CGSize)collectionViewContentSize { //Workaround
        CGSize superSize = [super collectionViewContentSize];
        CGRect frame = self.collectionView.frame;
        return CGSizeMake(fmaxf(superSize.width, CGRectGetWidth(frame)), fmaxf(superSize.height, CGRectGetHeight(frame)));
    }
    

提交回复
热议问题