Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

后端 未结 24 1375
野性不改
野性不改 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:58

    I use a variant of fz. answer (iOS 7 & 8) :

    Before rotation :

    1. Store the current visible index path
    2. Create a snapshot of the collectionView
    3. Put an UIImageView with it on top of the collection view

    After rotation :

    1. Scroll to the stored index
    2. Remove the image view.

      @property (nonatomic) NSIndexPath *indexPath;
      
      - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                      duration:(NSTimeInterval)duration {
          self.indexPathAfterRotation = [[self.collectionView indexPathsForVisibleItems] firstObject];
      
          // Creates a temporary imageView that will occupy the full screen and rotate.
          UIGraphicsBeginImageContextWithOptions(self.collectionView.bounds.size, YES, 0);
          [self.collectionView drawViewHierarchyInRect:self.collectionView.bounds afterScreenUpdates:YES];
          UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
      
          UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
          [imageView setFrame:[self.collectionView bounds]];
          [imageView setTag:kTemporaryImageTag];
          [imageView setBackgroundColor:[UIColor blackColor]];
          [imageView setContentMode:UIViewContentModeCenter];
          [imageView setAutoresizingMask:0xff];
          [self.view insertSubview:imageView aboveSubview:self.collectionView];
      
          [[self.collectionView collectionViewLayout] invalidateLayout];
      }
      
      - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
          [self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
      
          [[self.view viewWithTag:kTemporaryImageTag] removeFromSuperview];
      }
      

提交回复
热议问题