Swift - UICollectionView fixing center when rotate/landscape 방법
2021. 12. 29. 15:20ㆍDeveloper.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
}
}
반응형
'Developer.TokkiSea > Apple' 카테고리의 다른 글
framework not found CoreAudioTypes / AudioUnit 해결 방법 (1) | 2022.03.08 |
---|---|
420YpCbCr8 Conversion to ARGB , RGBA 변환 방법 (0) | 2022.03.03 |
RxSwift 정리 6 - UI (TableView .bind .drive .orEmpty) (0) | 2021.08.24 |
RxSwift 정리 5 - operators(.withLatestFrom .sample .amb .switchLatest .retry(when:)) (0) | 2021.08.23 |
RxSwift 정리 4 - operators(.startWith .concat .concatMap .marge .combineLatest .zip) (0) | 2021.08.23 |