Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

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

    The "just snap" answer above didn't work for me as it frequently didn't end on the item that was in view before the rotate. So I derived a flow layout that uses a focus item (if set) for calculating the content offset. I set the item in willAnimateRotationToInterfaceOrientation and clear it in didRotateFromInterfaceOrientation. The inset adjustment seems to be need on IOS7 because the Collection view can layout under the top bar.

    @interface HintedFlowLayout : UICollectionViewFlowLayout
    @property (strong)NSIndexPath* pathForFocusItem;
    @end
    
    @implementation HintedFlowLayout
    
    -(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];
        }
    }
    @end
    

提交回复
热议问题