Last active
February 16, 2023 04:29
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
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
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
I don't understand how we can use it🤔 self.collectionView.scrollToBottom(animated: true) - Value of type 'UICollectionView' has no member 'scrollToBottom'