I have created a CollectionView
Control and filled it with images. Now I want to scroll to item at a particular index on start. I have tried out scrollToItemA
This is based on @Womble's answer, all credit goes to them:
The method viewDidLayoutSubviews()
gets called repeatedly. For me (iOS 11.2) the first time it gets called the collectionView.contentSize
is {0,0}
. The second time, the contentSize
is correct. Therefore, I had to add a check for this:
var needsDelayedScrolling = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.needsDelayedScrolling = true
// ...
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.needsDelayedScrolling && collectionView.contentSize.width > 0 {
self.needsDelayedScrolling = false
self.collectionView!.scrollToItem(at: someIndexPath,
at: .centeredVertically,
animated: false)
}
}
}
After adding that extra && collectionView.contentSize.width > 0
it works beautifully.