Swift - UICollectionView fixing center when rotate/landscape 방법

2021. 12. 29. 15:20Developer.TokkiSea/Apple

반응형

임시 메모 글입니다.(나중에 다듬을거예요..)

 

아래 코드를 이용하면 콜렉션뷰의 가로/세로 보기 전환 시 편하게 진행중이던 index 에 고정 됩니다.

 

class RootPreviewVC: UIViewController {

  private lazy var collectionView: UICollectionView = {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
	...
    return collectionView
  }()
  
  
  private var prevIndexPathAtCenter: IndexPath?
  
  private var currentIndexPath: IndexPath? {
    let center = view.convert(collectionView.center, to: collectionView)
    return collectionView.indexPathForItem(at: center)
  }
  
  override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransition(to: newCollection, with: coordinator)
    if let indexAtCenter = currentIndexPath {
      prevIndexPathAtCenter = indexAtCenter
    }
    collectionView.collectionViewLayout.invalidateLayout()
  }
 
}

extension RootVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
    guard let oldCenter = prevIndexPathAtCenter else {
      return proposedContentOffset
    }
    let attrs =  collectionView.layoutAttributesForItem(at: oldCenter)
    let newOriginForOldIndex = attrs?.frame.origin
    return newOriginForOldIndex ?? proposedContentOffset
  }
}
반응형