Skip to content

Instantly share code, notes, and snippets.

@raxityo
Last active February 16, 2023 04:29
Show Gist options
  • Save raxityo/62cb48a25faa0c0eec65852c58f2d9c7 to your computer and use it in GitHub Desktop.
Save raxityo/62cb48a25faa0c0eec65852c58f2d9c7 to your computer and use it in GitHub Desktop.
UICollectionView extension to programmatically scroll to last item in the CollectionView (using datasource instead of scrollToVisibleRect).
import UIKit
extension UICollectionView {
// MARK: - UICollectionView scrolling/datasource
/// Last Section of the CollectionView
var lastSection: Int {
return numberOfSections - 1
}
/// IndexPath of the last item in last section.
var lastIndexPath: IndexPath? {
guard lastSection >= 0 else {
return nil
}
let lastItem = numberOfItems(inSection: lastSection) - 1
guard lastItem >= 0 else {
return nil
}
return IndexPath(item: lastItem, section: lastSection)
}
/// Islands: Scroll to bottom of the CollectionView
/// by scrolling to the last item in CollectionView
func scrollToBottom(animated: Bool) {
guard let lastIndexPath = lastIndexPath else {
return
}
scrollToItem(at: lastIndexPath, at: .bottom, animated: animated)
}
}
@NomadicWarrior
Copy link

I don't understand how we can use it🤔 self.collectionView.scrollToBottom(animated: true) - Value of type 'UICollectionView' has no member 'scrollToBottom'

@dohoudjann
Copy link

I don't understand how we can use it🤔 self.collectionView.scrollToBottom(animated: true) - Value of type 'UICollectionView' has no member 'scrollToBottom'

Placed DispatchQueue.main.async { self.collectionView.scrollToBottom(animated: false) } inside my api call after reloading my collectionView and it works like a charm

@glotcha
Copy link

glotcha commented Feb 16, 2023

or you can use the scrollView methods setContentOffset(CGPoint(x:0 , y: contentSize), animated: true)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment