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

别来无恙 提交于 2019-12-03 08:31:48
Timothy Moose

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

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

Swift 3 & 4, assuming you only have one section :

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

I would check first if theres is an option to scroll to bottom just in case something goes wrong with your data and your table/collection view doesn't have rows.

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

I was having an issue where I could scroll to the last item in the collection view, but was unable to scroll to the bottom of the footer.

The following code fixed that issue:

let bottomOffset = CGPoint(x: 0, 
                           y: collectionView.frame.height + (collectionView.contentSize.height * CGFloat(itemsInCollectionView.count)))
collectionView.setContentOffset(bottomOffset, animated: false)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!