Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Scroll CollectionView to bottom Programmatically

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

like image 320
PRAVEEN Avatar asked Nov 16 '16 09:11

PRAVEEN


3 Answers

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)
    }
}
like image 81
Yuchen Avatar answered Nov 18 '22 21:11

Yuchen


let lastItemIndex = NSIndexPath(forItem: data.count - 1, inSection: 0)
collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: .Bottom, animated: true)

dont forget about:
- atScrollPosition: .Bottom
- and you need to check is data.count > 0 beacause if data.count == 0 you will receive same error as you have

like image 41
Vadim Kozak Avatar answered Nov 18 '22 22:11

Vadim Kozak


You can animate your CollectionView to Bottom with the contentOffset also

Here is an example

let contentHeight: CGFloat = myCollectionView.contentSize.height
let heightAfterInserts: CGFloat = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom)
if contentHeight > heightAfterInserts {
    myCollectionView.setContentOffset(CGPoint(x: 0, y: myCollectionView.contentSize.height - myCollectionView.frame.size.height), animated: true) 
}
like image 28
Rajat Avatar answered Nov 18 '22 21:11

Rajat