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
Swift 5 & 4 Just Call this Function when you want to display the last cell of collectionview
//MARK:- Collection view Scroll to End
func funColvScrollToEnd()
{
let item = self.collectionView(self.colv!, numberOfItemsInSection: 0) - 1
let lastItemIndex = NSIndexPath(item: item, section: 0)
self.colv?.scrollToItem(at: lastItemIndex as IndexPath, at: .bottom, animated: false)
}
//MARK:- You can use .right/ .left/ .top/ .bottom
Swift 4
collectionView?.scrollToItem(at: IndexPath(item: 3, section: 0), at: UICollectionViewScrollPosition.top, animated: false)
Updated for Swift 3:
let item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
let lastItemIndex = IndexPath(item: item, section: 0)
collectionView?.scrollToItem(at: lastItemIndex, at: UICollectionViewScrollPosition.top, animated: true)
lstMessages.reloadData()
let item = self.collectionView(lstMessages, numberOfItemsInSection: 0) - 1
let lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
lstMessages.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false)
Where lstMessages is my collectionView
Swift 4.2
let lastSection = self.messagesCollectionView.numberOfSections - 1
let lastRow = self.messagesCollectionView.numberOfItems(inSection: lastSection)
let indexPath = IndexPath(row: lastRow - 1, section: lastSection)
self.messagesCollectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.top, animated: true)
Here's my take in Swift5:
extension UICollectionView {
public func scrollToLastItem(at scrollPosition: UICollectionView.ScrollPosition, adjustment: CGFloat = 0.0, withAdjustmentDuration duration: TimeInterval = 0.5) {
let lastSection = self.numberOfSections - 1
let lastRowInLastSection = self.numberOfItems(inSection: lastSection)
if lastSection > 0, lastRowInLastSection > 0 {
let indexPath = IndexPath(row: lastRowInLastSection - 1, section: lastSection)
let visibleIndexPaths = self.indexPathsForVisibleItems
if !visibleIndexPaths.contains(indexPath) {
self.self.scrollToItem(at: indexPath, at: scrollPosition, animated: true)
UIView.animate(withDuration: duration) {
switch scrollPosition {
case .top, .bottom, .centeredVertically:
self.contentOffset.y += adjustment
case .left, .right, .centeredHorizontally:
self.contentOffset.x += adjustment
default:
print("Inavlid scrollPosition: \(scrollPosition)")
}
}
}
}
}
}