Ios6 有没有办法自动滚动到UICollectionView的底部
因此,我目前正在处理一个项目,该项目有一个按钮,可将单元格添加到UICollectionView,然后需要自动滚动到最后一个单元格(即UICollectionView的底部) 我找到了方法Ios6 有没有办法自动滚动到UICollectionView的底部,ios6,uicollectionview,nsindexpath,Ios6,Uicollectionview,Nsindexpath,因此,我目前正在处理一个项目,该项目有一个按钮,可将单元格添加到UICollectionView,然后需要自动滚动到最后一个单元格(即UICollectionView的底部) 我找到了方法 scrollToItemAtIndexPath:(NSIndexPath*)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition动画:(BOOL)动画 但是现在我在尝试查找CollectionView中最后一个对象的
scrollToItemAtIndexPath:(NSIndexPath*)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition动画:(BOOL)动画
但是现在我在尝试查找CollectionView中最后一个对象的indepath
时遇到了麻烦
问题似乎在于我一直试图将UICollectionView中的单元格视为一个数组(不能通过它们枚举,不能响应lastObject
等等)。我能找到的最接近的方法是visibleItems
,它确实为我提供了一个数组,但当我需要添加到可见帧之外的单元格时,它没有帮助
有没有办法获取CollectionView中最后一个对象的IndexPath?您可以询问您的数据源:
NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
这是你的答案。。。如果您不想询问datasource 将其添加到您的
视图显示:
方法中
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];
Swift 3&4,假设您只有一个部分:
func scrollToBottom() {
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)
}
我首先检查是否有一个选项可以滚动到底部,以防数据出现问题,并且表/集合视图没有行
func scrollToBottomIfPossible() {
guard self.myRows.count > 0 else {
return
}
self.collectionView.scrollToItem(at: IndexPath(row: yourItems.count - 1, section: mySections.count), at: .bottom, animated: true)
}
我遇到了一个问题,我可以滚动到集合视图中的最后一个项,但无法滚动到页脚的底部 以下代码修复了该问题:
let bottomOffset = CGPoint(x: 0,
y: collectionView.frame.height + (collectionView.contentSize.height * CGFloat(itemsInCollectionView.count)))
collectionView.setContentOffset(bottomOffset, animated: false)
你的数据来源是什么?获取数据源的计数以确定最后一个索引路径如何?就是这样!非常感谢。我想我一直忽略了indexPath的
部分
,因此它看起来像[15],而不是[0,15]。还要注意,滚动位置UICollectionViewScrollPositionBottom
将滚动直到单元格刚好可见。如果要一直滚动到集合视图的底部(包括底部部分插图),请使用UICollectionViewScrollPositionTop
。我想您可以避免额外的两个变量lastIndex path和item,直接在scrollToItem方法中创建IndexXPath