Scroll UICollectionView to bottom
For Swift -
For Horizontal Scrolling - .right
For Vertical Scrolling - .bottom
override func viewDidLayoutSubviews() {
let section = 0
let lastItemIndex = self.dateCollectionView.numberOfItemsInSection(section) - 1
let indexPath:NSIndexPath = NSIndexPath.init(forItem: lastItemIndex, inSection: section)
self.dateCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .right, animated: false)
}
For Swift 3 and multiple sections
/**
This method scrolls the *UICollectionView* to the last item in the last section
*/
func scrollToLastItem() {
let lastSection = collectionView.numberOfSections - 1
let lastRow = collectionView.numberOfItems(inSection: lastSection)
let indexPath = IndexPath(row: lastRow - 1, section: lastSection)
self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
}
I have added the lines below to run once the query is complete.
var item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
var lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false)
Update to Swift 5
let item = self.collectionView(self.collectionView, numberOfItemsInSection: 0) - 1
let lastItemIndex = IndexPath(item: item, section: 0)
self.collectionView.scrollToItem(at: lastItemIndex, at: .top, animated: true)
Updated for Swift 3:
let item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
let lastItemIndex = IndexPath(item: item, section: 0)
collectionView?.scrollToItem(at: lastItemIndex, at: UICollectionViewScrollPosition.top, animated: true)