Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

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

    What does the job for me is this:

    1. Set the size of your my cells from your my UICollectionViewDelegateFlowLayout method

      func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize
      {
          return collectionView.bounds.size
      }
      
    2. After that I implement willRotateToInterfaceOrientationToInterfaceOrientation:duration: like this

      override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) 
      {
          let currentPage = Int(collectionView.contentOffset.x / collectionView.bounds.size.width)
      
          var width = collectionView.bounds.size.height
          UIView.animateWithDuration(duration) {
              self.collectionView.setContentOffset(CGPointMake(width * CGFloat(currentPage), 0.0), animated: false)
              self.collectionView.collectionViewLayout.invalidateLayout()
          }
      }
      

    The above code is in Swift but you get the point and it's easy to "translate"

提交回复
热议问题