Dynamically setting layout on UICollectionView causes inexplicable contentOffset change

前端 未结 10 1642
一生所求
一生所求 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:30

    This issue bit me as well and it seems to be a bug in the transition code. From what I can tell it tries to focus on the cell that was closest to the center of the pre-transition view layout. However, if there doesn't happen to be a cell at the center of the view pre-transition then it still tries to center where the cell would be post-transition. This is very clear if you set alwaysBounceVertical/Horizontal to YES, load the view with a single cell and then perform a layout transition.

    I was able to get around this by explicitly telling the collection to focus on a specific cell (the first cell visible cell, in this example) after triggering the layout update.

    [self.collectionView setCollectionViewLayout:[self generateNextLayout] animated:YES];
    
    // scroll to the first visible cell
    if ( 0 < self.collectionView.indexPathsForVisibleItems.count ) {
        NSIndexPath *firstVisibleIdx = [[self.collectionView indexPathsForVisibleItems] objectAtIndex:0];
        [self.collectionView scrollToItemAtIndexPath:firstVisibleIdx atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
    }
    

提交回复
热议问题