I would like to scroll the UICollectionView to the bottom so the last item is in the view. I have tried to use scrollToItemAtIndexPath but it does not seem to be working. I want
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)
You can track top and bottom of your visible view and load next page of items
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
print("bottom")
}
if (scrollView.contentOffset.y <= 0) {
print("top")
}
}
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)
}
Update for Swift 3
func viewScrollButton() {
let lastItem = collectionView(self.collectionView!, numberOfRowsInSection: 0) - 1
let indexPath: NSIndexPath = NSIndexPath.init(item: lastItem, section: 0)
self.collectionView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: false)
}
Swift 4:
For Horizontal Scrolling - .right
For Vertical Scrolling - .bottom
let lastItemIndex = self.collectionView.numberOfItems(inSection: 0) - 1
let indexPath:IndexPath = IndexPath(item: lastItemIndex, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .right, animated: false)