Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

后端 未结 24 1412
野性不改
野性不改 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 07:59

    This problem bothered me for a bit as well. The highest voted answered seemed a bit too hacky for me so I just dumbed it down a bit and just change the alpha of the collection view respectively before and after rotation. I also don't animate the content offset update.

    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    {
    self.collectionView.alpha = 0;
    [self.collectionView.collectionViewLayout invalidateLayout];
    
    self.scrollPositionBeforeRotation = CGPointMake(self.collectionView.contentOffset.x / self.collectionView.contentSize.width,
                                                    self.collectionView.contentOffset.y / self.collectionView.contentSize.height);
    }
    
    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
    {
    CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x * self.collectionView.contentSize.width,
                                           self.scrollPositionBeforeRotation.y * self.collectionView.contentSize.height);
    
    [self.collectionView setContentOffset:newContentOffset animated:NO];
    self.collectionView.alpha = 1;
    }
    

    Fairly smooth and less hacky.

提交回复
热议问题