UICollectionView automatically scroll to bottom when screen loads UICollectionView automatically scroll to bottom when screen loads ios ios

UICollectionView automatically scroll to bottom when screen loads


I found that nothing would work in viewWillAppear. I can only get it to work in viewDidLayoutSubviews:

- (void)viewDidLayoutSubviews{    [super viewDidLayoutSubviews];    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:endOfModel inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];}


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];}


matomo