Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

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

    Swift 4.2 subclass:

    class RotatableCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
        private var focusedIndexPath: IndexPath?
    
        override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
            super.prepare(forAnimatedBoundsChange: oldBounds)
            focusedIndexPath = collectionView?.indexPathsForVisibleItems.first
        }
    
        override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
            guard let indexPath = focusedIndexPath
                , let attributes = layoutAttributesForItem(at: indexPath)
                , let collectionView = collectionView else {
                    return super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
            }
            return CGPoint(x: attributes.frame.origin.x - collectionView.contentInset.left,
                           y: attributes.frame.origin.y - collectionView.contentInset.top)
        }
    
        override func finalizeAnimatedBoundsChange() {
            super.finalizeAnimatedBoundsChange()
            focusedIndexPath = nil
        }
    }
    

提交回复
热议问题