Last Updated: August 17, 2018
·
20.17K
· widescape

UICollectionView: Set Initial ContentOffset

A UICollectionViewLayout doesn't inform the controller when it is actually rendering the layout. A UICollectionViewLayout could even start to render after the controller received viewDidLayoutSubviews or viewDidAppear.

The trick is to force the UICollectionViewLayout to render its layout by calling [self.collectionView.collectionViewLayout collectionViewContentSize];

@implementation YourViewController

BOOL _viewDidLayoutSubviewsForTheFirstTime = YES;

- (void)viewDidLoad
{
  [super viewDidLoad];
  _viewDidLayoutSubviewsForTheFirstTime = YES;
}

- (void)viewDidLayoutSubviews
{
  [super viewDidLayoutSubviews];
  // Only scroll when the view is rendered for the first time
  if (_viewDidLayoutSubviewsForTheFirstTime) {
    _viewDidLayoutSubviewsForTheFirstTime = NO;
    // Calling collectionViewContentSize forces the UICollectionViewLayout to actually render the layout
    [self.collectionView.collectionViewLayout collectionViewContentSize];
    // Now you can scroll to your desired indexPath or contentOffset
    [self.collectionView scrollToItemAtIndexPath:yourDesiredIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
  }
}

Note: If your collectionView is not the root view of your controller, you need to wait until viewDidLayoutSubviews until you can interact with the collection view.

1 Response
Add your response

Excellent, thanks.

over 1 year ago ·