Search code examples
iosios7scrolluicollectionview

scrollToItemAtIndexPath before the view is shown the first time


I have a UIView where I added a UICollectionView. Now this view is shown on app start up. At the same time I'm scrolling to a certain position in my collection view. Therefore I use scrollToItemAtIndexPath. The problem now is that it scrolls to a wrong position, because the collection view has the wrong size at the beginning: If you start the iPad in the landscape orientation on iOS 7 the collection view always takes 768 as width despite it is in landscape.

How can I scroll to a certain position without the user noticing it? Where in the view hierarchy can I call it?

viewWillAppear: frames have not been set
viewDidAppear: not possible without the user noticing it
layoutSubviews: this is called multiple times and I only need it at startup and when the user presses a button

I also tried to use layoutIfNeeded, but that doesn't help for my edge case (iOS 7, iPad, landscape at startup).


Solution

  • Constraints kick around the time viewDidAppear and layoutSubviews is called for the last time. By that time it's too late.

    You can try inheriting your own class from UICollectionView and see if its layoutSubviews has correct constraints and call scrollToIndex from there.

    If that fails, you can cheat by setting frame sizes in viewDidLoad and calling scroll to index. ( This one is a tad bit more complicated) –