Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

后端 未结 24 1395
野性不改
野性不改 2020-12-04 07:22

I\'m trying to handle interface orientation changes in a UICollectionViewController. What I\'m trying to achieve is, that I want to have the same contentOffset afte

24条回答
  •  长情又很酷
    2020-12-04 08:10

    After rotate interface orientation the UICollectionViewCell usually move to another position, because we won't update contentSize and contentOffset.

    So the visible UICollectionViewCell always not locate at expected position.

    The visible UICollectionView which we expected image as follow

    Orientation which we expected

    UICollectionView must delegate the function [collectionView sizeForItemAtIndexPath] of『UICollectionViewDelegateFlowLayout』.

    And you should calculate the item Size in this function.

    The custom UICollectionViewFlowLayout must override the functions as follow.

    1. -(void)prepareLayout

      . Set itemSize, scrollDirection and others.

    2. -(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

      . Calculate page number or calculate visible content offset.

    3. -(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset

      . Return visual content offset.

    4. -(CGSize)collectionViewContentSize

      . Return the total content size of collectionView.

    Your viewController must override 『willRotateToInterfaceOrientation』and in this function you should call the function [XXXCollectionVew.collectionViewLayout invalidateLayout];

    But 『willRotateToInterfaceOrientation』 is deprecated in iOS 9, or you could call the function [XXXCollectionVew.collectionViewLayout invalidateLayout] in difference way.

    There's an example as follow : https://github.com/bcbod2002/CollectionViewRotationTest

提交回复
热议问题