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]'
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)
}
}
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With