有没有办法自动滚动到UICollectionView的底部

问题描述 投票:4回答:5

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

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

但现在我陷入困境,试图找到CollectionView中最后一个对象的indexPath

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

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

ios6 uicollectionview nsindexpath
5个回答
15
投票

你可以问你的数据来源:

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

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

1
投票

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

0
投票

我会首先检查是否可以选择滚动到底部,以防万一您的数据出现问题并且您的表/集合视图没有行。

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

0
投票

我有一个问题,我可以滚动到集合视图中的最后一项,但无法滚动到页脚的底部。

以下代码修复了该问题:

let bottomOffset = CGPoint(x: 0, 
                           y: collectionView.frame.height + (collectionView.contentSize.height * CGFloat(itemsInCollectionView.count)))
collectionView.setContentOffset(bottomOffset, animated: false)
© www.soinside.com 2019 - 2024. All rights reserved.