Reputation: 935
I have a UICollectionView
with 2 sections with different data. I'm trying to load more data in section when user scrolls over 20 cells in a section.
For example:
Section 0 and 1 have both 20 cells.
When I scroll through all 20 cells in section 0, it should load more data into that section and end up with 40 cells in Section 0 and 20 cells in Section 1.
This is what I have, but it doesn't work as expected:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
if indexPath.row == popularMovies.count {
print("Section 0, Row \(indexPath.row) - Loading more popular movies...")
}
break
case 1:
if indexPath.row == nowPlayingMovies.count {
print("Section 1, Row \(indexPath.row) - Loading more now streaming movies...")
}
break
default: break
}
}
Section 1, Row 19 - Loading more now streaming movies... <--- this is printed when hit cell 13 in section 0
Section 0, Row 19 - Loading more popular movies... <--- this is printed as expected when hit cell 20 in section 0
Is it even possible?
Upvotes: 0
Views: 365
Reputation: 17882
Check out UICollectionViewDataSourcePrefetching
, this can be easily used to implement to load more data when scrolling, in addition to e.g. preloading of images for cells that are about to be scrolled into the visibible area.
For example:
extension MoviesViewController: UICollectionViewDataSourcePrefetching {
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
let maxItem = indexPaths.map { $0.item }.max() ?? 0
if maxItem >= self.popularMovies.count - 3 {
// load new movies
}
}
}
Upvotes: 1