Ios – How to Scroll CollectionView to bottom Programmatically

iosiphoneswiftuicollectionview

I used this code for scrolling the collection View:

let section = (self.collectionView?.numberOfSections)! - 1;
let item = (self.collectionView?.numberOfItems(inSection: section))! - 1;
let lastIndexPath = IndexPath(item: item, section: section);
self.collectionView?.scrollToItem(at: lastIndexPath, at: .bottom, animated: true);

But I get error :

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 ..
0]'

Best Answer

Swift 4+

extension UICollectionView {
    func scrollToLast() {
        guard numberOfSections > 0 else {
            return
        }

        let lastSection = numberOfSections - 1

        guard numberOfItems(inSection: lastSection) > 0 else {
            return
        }

        let lastItemIndexPath = IndexPath(item: numberOfItems(inSection: lastSection) - 1,
                                          section: lastSection)
        scrollToItem(at: lastItemIndexPath, at: .bottom, animated: true)
    }
}
Related Topic