2013-06-06 54 views
3

所以我目前正在一个项目,有一个按钮,将单元格添加到UICollectionView,然后需要自动滚动到最后一个单元格(即底部UICollectionView)。有没有办法自动滚动到UICollectionView的底部

我已经找到了方法 scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated

但现在我越来越被困在试图找到在的CollectionView的最后一个对象的indexPath

这个问题似乎在于我一直在试图将UICollectionView中的单元看作一个数组(不能通过它们枚举,不会对lastObject等作出响应)。最近似乎可以得到的方法是visibleItems其中确实给了我一个数组,但是当我需要在可见帧之外添加的单元格时无法帮助。

有没有办法在CollectionView中获取最后一个对象的IndexPath?

+0

什么是数据源?如何获得数据源的计数以确定最后的索引路径? –

回答

15

你可以只问你的数据源:

NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1; 
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1; 
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section]; 
+0

就是这样!谢谢!我想我一直忽略indexPath的'section'部分,使它看起来像[15],而不是[0,15],这给了我。 – cchapman

+2

还要注意,滚动位置'UICollectionViewScrollPositionBottom'将滚动,直到单元格刚好可见。如果您想一直滚动到集合视图的底部,包括底部插入部分,请使用'UICollectionViewScrollPositionTop'。 – devios1

+0

是啊,.bottom不会滚动到底部和顶部,谁知道... – jarryd

2

这里是你的答案...如果你想问的数据源。

将其添加到您的viewDidAppear:方法中。

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

对于斯威夫特3,假设你只有一个部分:

let section = 0 
let item = collectionView.numberOfItems(inSection: section) - 1 
let lastIndexPath = IndexPath(item: item, section: section) 
collectionView.scrollToItem(at: lastIndexPath, at: .bottom, animated: false)