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.
Written by Robert Wünsch
Related protips
1 Response
Excellent, thanks.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Cocoa touch
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#