I was able to get it to auto scroll to the top upon opening the app, but now it won't let you scroll anymore because of the scrollView
forcefully keeping it at the top due to willDisplay
.
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if info.count > 0 {
collectionView.scrollToItem(at: IndexPath(item:info.count - 1, section: 0), at: .top, animated: false)
}
}
Where else can I put it?
Use the following code to achieve your needs. For animation, you just need to pass value true/false in animated of scrollToRow
function.
Hope this will help you!
To scroll top without animation
func scrollToTopWithoutAnimation() {
DispatchQueue.main.async {
if self.dataArray.count > 0 {
let indexPath = IndexPath(row: 0, section: 0)
collectionView.scrollToItem(at: indexPath, at: .top, animated: false)
}
}
}
To scroll top with animation
func scrollToTopWithAnimation() {
DispatchQueue.main.async {
if self.dataArray.count > 0 {
let indexPath = IndexPath(row: 0, section: 0)
collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
}
}
}