Swift-如何获取indexPath.row或类似的部分



我有一个UICollectionView,它有两个不同数据的部分。当用户在一个分区中滚动20个单元格时,我试图在分区中加载更多数据。

例如:

第0节和第1节都有20个单元格。

当我滚动浏览第0节中的所有20个单元格时,它应该会将更多的数据加载到该节中,并最终在第0节和第1节中分别加载40个单元格和20个单元格。

这就是我所拥有的,但它并没有像预期的那样工作:

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

这可能吗?

查看UICollectionViewDataSourcePrefetching,它可以很容易地用于在滚动时加载更多数据,此外还可以预加载即将滚动到可视区域的单元格的图像。

例如:

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
}
}
}

最新更新