Last Updated: February 25, 2016
· widescape
P1040280 profil

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.

Say Thanks

1 Response
Add your response

445105 13 young angry rin

Excellent, thanks.

over 1 year ago ·