Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically scroll to the bottom of a UICollectionView

So I'm currently working on a project that has a button that adds cells to a UICollectionView and then needs to automatically scroll to the last cell (i.e. the bottom of the UICollectionView).

I've found the method scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated

But now I'm getting stuck at trying to find the indexPath of the last object in the CollectionView.

The problem seems to lie in that I've been trying to think of the cells in the UICollectionView as an array (can't enumerate through them, doesn't respond to lastObject and so on). The closest I can seem to get is the method visibleItems which does give me an array but doesn't help when I need cells that are added outside of the visible frame.

Is there a way to get the IndexPath for that last object in the CollectionView?

like image 613
cchapman Avatar asked Jun 06 '13 07:06

cchapman


2 Answers

You can just ask your data source:

NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
like image 131
Timothy Moose Avatar answered Jan 03 '23 23:01

Timothy Moose


Here is your answer... If you don't want to ask datasource.

Add it in your viewDidAppear: method.

NSInteger section = [_collectionView numberOfSections] - 1 ;
NSInteger item = [_collectionView numberOfItemsInSection:section] - 1 ;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section] ;
[_collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:(UICollectionViewScrollPositionBottom) animated:YES];
like image 25
itsji10dra Avatar answered Jan 04 '23 01:01

itsji10dra