Search code examples
iosobjective-cipaduicollectionview

UICollectionView current visible cell index


I am using UICollectionView first time in my iPad application. I have set UICollectionView such that its size and cell size is same, means only once cell is displayed at a time.

Problem: Now when user scroll UICollectionView I need to know which cell is visible I have to update other UI elements on change. I didn't find any delegate method for this. How can I achieve this?

Code:

[self.mainImageCollection setTag:MAIN_IMAGE_COLLECTION_VIEW];
[self.mainImageCollection registerClass:[InspirationMainImageCollectionCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.mainImageFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.mainImageFlowLayout setMinimumInteritemSpacing:0.0f];
[self.mainImageFlowLayout setMinimumLineSpacing:0.0f];
self.mainImageFlowLayout.minimumLineSpacing = 0;
[self.mainImageCollection setPagingEnabled:YES];
[self.mainImageCollection setShowsHorizontalScrollIndicator:NO];
[self.mainImageCollection setCollectionViewLayout:self.mainImageFlowLayout];

What I have tried:

As UICollectionView conforms to UIScrollView, I got when user scroll ends with UIScrollViewDelegate method

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

But inside above function how can I get current visible cell index of UICollectionView ?


Solution

  • The method [collectionView visibleCells] give you all visibleCells array you want. Use it when you want to get

    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
        for (UICollectionViewCell *cell in [self.mainImageCollection visibleCells]) {
            NSIndexPath *indexPath = [self.mainImageCollection indexPathForCell:cell];
            NSLog(@"%@",indexPath);
        }
    }
    

    Update to Swift 5:

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        for cell in yourCollectionView.visibleCells {
            let indexPath = yourCollectionView.indexPath(for: cell)
            print(indexPath)
        }
    }