Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView automatically scroll to bottom when screen loads

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 touched, but I'd like to be able to do that automatically when the view loads as well. The below works fine if I want to scroll to the bottom when the status bar is touched.

- (BOOL)scrollViewShouldScrollToTop:(UITableView *)tableView { NSLog(@"Detect status bar is touched."); [self scrollToBottom]; return NO; }  -(void)scrollToBottom {//Scrolls to bottom of scroller  CGPoint bottomOffset = CGPointMake(0, collectionViewReload.contentSize.height -     collectionViewReload.bounds.size.height);  [collectionViewReload setContentOffset:bottomOffset animated:NO];  } 

I've tried calling [self scrollToBottom] in the viewDidLoad. This isn't working. Any ideas on how I can scroll to the bottom when the view loads?

like image 634
SNV7 Avatar asked Feb 07 '13 20:02

SNV7


2 Answers

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]; } 
like image 160
Will Larche Avatar answered Sep 27 '22 22:09

Will Larche


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).

like image 41
Firo Avatar answered Sep 27 '22 22:09

Firo