I\'m trying to figure out how to scroll all the way to the bottom of a UICollectionView when the screen first loads. I\'m able to scroll to the bottom when the status bar is tou
The issue is likely that even if your collection view is on screen, it might not have the actual contentSize
.
If you scroll in viewDidAppear
, you will have a contentSize
, but your scollectionview will briefly show content before scrolling.
And the problem with viewDidLayoutSubviews
is that it is called multiple times, so you then need to add an ugly boolean to limit scrolling.
The best solution i've found is to force layout in view will appear.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// force layout before scrolling to most recent
collectionView.layoutIfNeeded()
// now you can scroll however you want
// e.g. scroll to the right
let offset = collectionView.contentSize.width - collectionView.bounds.size.width
collectionView.setContentOffSet(CGPoint(x: offset, y: 0), animated: animated)
}