Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

后端 未结 24 1406
野性不改
野性不改 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条回答
  •  猫巷女王i
    2020-12-04 08:17

    To piggy back off troppoli's solution you can set the offset in your custom class without having to worry about remembering to implement the code in your view controller. prepareForAnimatedBoundsChange should get called when you rotate the device then finalizeAnimatedBoundsChange after its done rotating.

    @interface OrientationFlowLayout ()
    
    @property (strong)NSIndexPath* pathForFocusItem;
    
    @end
    
    @implementation OrientationFlowLayout
    
    - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset {
        if (self.pathForFocusItem) {
            UICollectionViewLayoutAttributes* layoutAttrs = [self layoutAttributesForItemAtIndexPath:
                                                             self.pathForFocusItem];
            return CGPointMake(layoutAttrs.frame.origin.x - self.collectionView.contentInset.left,
                               layoutAttrs.frame.origin.y - self.collectionView.contentInset.top);
        }
        else {
            return [super targetContentOffsetForProposedContentOffset:proposedContentOffset];
        }
    }
    
    - (void)prepareForAnimatedBoundsChange:(CGRect)oldBounds {
        [super prepareForAnimatedBoundsChange:oldBounds];
        self.pathForFocusItem = [[self.collectionView indexPathsForVisibleItems] firstObject];
    }
    
    - (void)finalizeAnimatedBoundsChange {
        [super finalizeAnimatedBoundsChange];
        self.pathForFocusItem = nil;
    }
    
    @end
    

提交回复
热议问题