How we can get visible Cell IndexPath when a UICollectionView Loads its data initially

Avijit Das picture Avijit Das · Sep 11, 2014 · Viewed 7.9k times · Source

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];


}

Answer

dopcn picture dopcn · Sep 11, 2014

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;