Reputation: 300
Is there any way that we can get indexPathsForVisibleItems when a UICollectionView loads its data initially . Basically I want all cell indexPaths which are currently visible on the screen. I am getting that in scrollViewDidScroll using below code.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self LoadVisibleItems];
}
-(void)LoadVisibleItems
{
NSArray* visibleCellIndex = self.myCollectionView.indexPathsForVisibleItems;
NSArray *sortedIndexPaths = [visibleCellIndex sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSIndexPath *path1 = (NSIndexPath *)obj1;
NSIndexPath *path2 = (NSIndexPath *)obj2;
return [path1 compare:path2];
}];
NSIndexPath* newFirstVisibleCell = [sortedIndexPaths firstObject];
NSIndexPath* newLastVisibleCell = [sortedIndexPaths lastObject];
}
Upvotes: 2
Views: 8040
Reputation: 350
Try
[self.collectionView layoutIfNeeded];
NSArray *ary = collectionView.visibleCells;
for (UICollectionViewCell *cell in ary) {
NSIndexPath *path = [collectionView indexPathForCell:cell];
NSLog(@"indexPath of cell: %d - %d", (int)path.section, (int)path.row);
}
or use
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
}
Upvotes: 2
Reputation: 4218
Correct me if I misunderstand your question
If you load collectionView from storyboard
- (void) viewDidLoad {
[super viewDidLoad];
NSArray* visibleCellIndex = self.myCollectionView.indexPathsForVisibleItems;
}
If you init collectionView by code after some view addSubview
collectionView do
NSArray* visibleCellIndex = self.myCollectionView.indexPathsForVisibleItems;
Upvotes: 6