mlin956
mlin956

Reputation: 365

UICollectionView indexPathsForVisibleItems not working for some case

I have a UICollectionView with each page be the exactly same size as the screen. The scroll direction is horizontal. I want to get the current visible cells while the view is scrolling.

For example, if i'm on one whole page, I just get this page's index, if I'm scrolling in the middle of two pages, then I can get these two pages index. I know there is indexPathsForVisibleItems method. It works for the case when scrolling in the middle. It will return two cells' index.

But if I'm on a whole page, it will return two pages as well. More strange, this happens on my iPhone 7 Plus, but when I test it on iPhone 6s, it works fine and return the current page's single index.

Seems the method doesn't work for larger screens?

My collection view:

    CGSize screenSize = [UIScreen mainScreen].fixedBounds.size;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0.0;
    flowLayout.minimumInteritemSpacing = 0.0;
    flowLayout.itemSize = screenSize;

    UIColloctionView *collectionView =
        [[UICollectionView alloc] initWithFrame:SCRectMakeWithSize(screenSize) collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.scrollsToTop = NO;
    collectionView.pagingEnabled = YES;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;

The method i used to get current visible index:

    NSArray<NSIndexPath *> *indexPaths = [_tabsCollectionView indexPathsForVisibleItems];

On larger screen, this will return 2 items when I'm viewing the whole page.

Upvotes: 3

Views: 4018

Answers (1)

Ujwal Agrawal
Ujwal Agrawal

Reputation: 474

Even I was facing the similar type of issue.

The workaround that has worked for me is below

Swift 3 Solution

    var visibleRect    = CGRect()
    visibleRect.origin = collectionView.contentOffset
    visibleRect.size   = collectionView.bounds.size
    let visiblePoint   = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

    guard let visibleIndexPath: IndexPath = collectionView.indexPathForItem(at: visiblePoint) else { return }
    print(visibleIndexPath)

Hope this solution works for you.

Upvotes: 6

Related Questions