Keeping the contentOffset in a UICollectionView wh

2019-01-12 19:15发布

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 after an interface rotation. Meaning, that it should be changed corresponding to the ratio of the bounds change.

Starting in portrait with a content offset of {bounds.size.width * 2, 0} …

UICollectionView in portait

… should result to the content offset in landscape also with {bounds.size.width * 2, 0} (and vice versa).

UICollectionView in landscape

Calculating the new offset is not the problem, but don't know, where (or when) to set it, to get a smooth animation. What I'm doing so fare is invalidating the layout in willRotateToInterfaceOrientation:duration: and resetting the content offset in didRotateFromInterfaceOrientation::

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                duration:(NSTimeInterval)duration;
{
    self.scrollPositionBeforeRotation = CGPointMake(self.collectionView.contentOffset.x / self.collectionView.contentSize.width,
                                                    self.collectionView.contentOffset.y / self.collectionView.contentSize.height);
    [self.collectionView.collectionViewLayout invalidateLayout];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
    CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x * self.collectionView.contentSize.width,
                                           self.scrollPositionBeforeRotation.y * self.collectionView.contentSize.height);
    [self.collectionView newContentOffset animated:YES];
}

This changes the content offset after the rotation.

How can I set it during the rotation? I tried to set the new content offset in willAnimateRotationToInterfaceOrientation:duration: but this results into a very strange behavior.

An example can be found in my Project on GitHub.

23条回答
Viruses.
2楼-- · 2019-01-12 19:35

Use <CollectionViewDelegateFlowLayout> and in the method didRotateFromInterfaceOrientation: reload data of the CollectionView.

Implement collectionView:layout:sizeForItemAtIndexPath: method of <CollectionViewDelegateFlowLayout> and in the method verify the Interface orientation and apply your custom size of each cell.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    if (UIInterfaceOrientationIsPortrait(orientation)) {

        return CGSizeMake(CGFloat width, CGFloat height);

    } else {

        return CGSizeMake(CGFloat width, CGFloat height);

    }

}
查看更多
贪生不怕死
3楼-- · 2019-01-12 19:36

After rotate interface orientation the UICollectionViewCell usually move to another position, because we won't update contentSize and contentOffset.

So the visible UICollectionViewCell always not locate at expected position.

The visible UICollectionView which we expected image as follow

Orientation which we expected

UICollectionView must delegate the function [collectionView sizeForItemAtIndexPath] of『UICollectionViewDelegateFlowLayout』.

And you should calculate the item Size in this function.

The custom UICollectionViewFlowLayout must override the functions as follow.

  1. -(void)prepareLayout

    . Set itemSize, scrollDirection and others.

  2. -(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

    . Calculate page number or calculate visible content offset.

  3. -(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset

    . Return visual content offset.

  4. -(CGSize)collectionViewContentSize

    . Return the total content size of collectionView.

Your viewController must override 『willRotateToInterfaceOrientation』and in this function you should call the function [XXXCollectionVew.collectionViewLayout invalidateLayout];

But 『willRotateToInterfaceOrientation』 is deprecated in iOS 9, or you could call the function [XXXCollectionVew.collectionViewLayout invalidateLayout] in difference way.

There's an example as follow : https://github.com/bcbod2002/CollectionViewRotationTest

查看更多
甜甜的少女心
4楼-- · 2019-01-12 19:36

If found that using targetContentOffsetForProposedContentOffset does not work in all scenarios and the problem with using didRotateFromInterfaceOrientation is that it gives visual artifacts. My perfectly working code is as follows:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    _indexPathOfFirstCell = [self indexPathsForVisibleItems].firstObject;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    if (_indexPathOfFirstCell) {
        [UIView performWithoutAnimation:^{
            [self scrollToItemAtIndexPath:self->_indexPathOfFirstCell atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
        }];
        _indexPathOfFirstCell = nil;
    }
}

The key is to use the willRotateToInterfaceOrientation method to determine the part in the view that you want to scroll to and willAnimationRotationToInterfaceOrientation to recalculate it when the view has changed its size (the bounds have already changed when this method is called by the framework) and to actually scroll to the new position without animation. In my code I used the index path for the first visual cell to do that, but a percentage of contentOffset.y/contentSize.height would also do the job in slightly different way.

查看更多
5楼-- · 2019-01-12 19:38

This problem bothered me for a bit as well. The highest voted answered seemed a bit too hacky for me so I just dumbed it down a bit and just change the alpha of the collection view respectively before and after rotation. I also don't animate the content offset update.

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
self.collectionView.alpha = 0;
[self.collectionView.collectionViewLayout invalidateLayout];

self.scrollPositionBeforeRotation = CGPointMake(self.collectionView.contentOffset.x / self.collectionView.contentSize.width,
                                                self.collectionView.contentOffset.y / self.collectionView.contentSize.height);
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x * self.collectionView.contentSize.width,
                                       self.scrollPositionBeforeRotation.y * self.collectionView.contentSize.height);

[self.collectionView setContentOffset:newContentOffset animated:NO];
self.collectionView.alpha = 1;
}

Fairly smooth and less hacky.

查看更多
6楼-- · 2019-01-12 19:38

I solved this problem with Following Steps:

  1. Calculate currently scrolled NSIndexPath
  2. Disable Scrolling and Pagination in UICollectionView
  3. Apply new Flow Layout to UICollectionView
  4. Enable Scrolling and Pagination in UICollectionView
  5. Scroll UICollectionView to current NSIndexPath

Here is the Code Template demonstrating the Above Steps:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                            duration:(NSTimeInterval)duration;
{
     //Calculating Current IndexPath
     CGRect visibleRect = (CGRect){.origin = self.yourCollectionView.contentOffset, .size = self.yourCollectionView.bounds.size};
     CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
     self.currentIndexPath = [self.yourCollectionView indexPathForItemAtPoint:visiblePoint];

     //Disable Scrolling and Pagination
     [self disableScrolling];

     //Applying New Flow Layout
     [self setupNewFlowLayout];

     //Enable Scrolling and Pagination
     [self enableScrolling];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
     //You can also call this at the End of `willRotate..` method.
     //Scrolling UICollectionView to current Index Path
     [self.yourCollectionView scrollToItemAtIndexPath:self.currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}

- (void) disableScrolling
{
    self.yourCollectionView.scrollEnabled   = false;
    self.yourCollectionView.pagingEnabled   = false;
}

- (void) enableScrolling
{
    self.yourCollectionView.scrollEnabled   = true;
    self.yourCollectionView.pagingEnabled   = true;
}

- (void) setupNewFlowLayout
{
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    [flowLayout setItemSize:CGSizeMake(EXPECTED_WIDTH, EXPECTED_HEIGHT)];

    [self.yourCollectionView setCollectionViewLayout:flowLayout animated:YES];
    [self.yourCollectionView.collectionViewLayout invalidateLayout];
}

I hope this helps.

查看更多
Animai°情兽
7楼-- · 2019-01-12 19:42

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
查看更多
登录 后发表回答