self.collectionView.indexPathsForVisibleItems是一個包含了當前可見的所有cell的indexPath的數(shù)組森枪,但它并不一定是按照顯示順序排列的辽社,因為UICollectionView的cell可以以任意的順序被加載和顯示喘先。
例如楷扬,在UICollectionView中解幽,如果用戶快速滑動,會出現(xiàn)這樣的情況:先加載在后面的cell烘苹,然后再加載在前面的cell躲株,這樣就會導致self.collectionView.indexPathsForVisibleItems數(shù)組的順序與顯示順序不一致。
如果需要按照顯示順序來處理可見的cell镣衡,可以使用visibleCells屬性獲取所有可見的cell霜定,并按照它們在UICollectionView中的位置來排序。例如廊鸥,可以使用以下代碼對可見的cell按照它們在UICollectionView中的位置進行排序:
NSArray *visibleCells = [self.collectionView visibleCells];
NSArray *sortedCells = [visibleCells sortedArrayUsingComparator:^NSComparisonResult(UICollectionViewCell *cell1, UICollectionViewCell *cell2) {
NSIndexPath *indexPath1 = [self.collectionView indexPathForCell:cell1];
NSIndexPath *indexPath2 = [self.collectionView indexPathForCell:cell2];
return [indexPath1 compare:indexPath2];
}];
或者:
NSArray *visibleIndexPaths = self.collectionView.indexPathsForVisibleItems;
NSArray *sortedIndexPaths = [visibleIndexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *indexPath1, NSIndexPath *indexPath2) {
return [indexPath1 compare:indexPath2];
}];