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
Consider if you can use performBatchUpdates
like this:
private func reloadAndScrollToItem(at index: Int, animated: Bool) {
collectionView.reloadData()
collectionView.performBatchUpdates({
self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0),
at: .bottom,
animated: animated)
}, completion: nil)
}
If index
is the index of the last item in the collection's view data source it'll scroll all the way to the bottom.
Just to elaborate on my comment.
viewDidLoad is called before elements are visual so certain UI elements cannot be manipulated very well. Things like moving buttons around work but dealing with subviews often does not (like scrolling a CollectionView).
Most of these actions will work best when called in viewWillAppear or viewDidAppear. Here is an except from the Apple docs that points out an important thing to do when overriding either of these methods:
You can override this method to perform additional tasks associated with presenting the view. If you override this method, you must call super at some point in your implementation.
The super call is generally called before custom implementations. (so the first line of code inside of the overridden methods).
So had a similar issue and here is another way to come at it without using scrollToItemAtIndexPath
This will scroll to the bottom only if the content is larger than the view frame.
It's probably better to use scrollToItemAtIndexPath but this is just another way to do it.
CGFloat collectionViewContentHeight = myCollectionView.contentSize.height;
CGFloat collectionViewFrameHeightAfterInserts = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom);
if(collectionViewContentHeight > collectionViewFrameHeightAfterInserts) {
[myCollectionView setContentOffset:CGPointMake(0, myCollectionView.contentSize.height - myCollectionView.frame.size.height) animated:NO];
}