kusumoto_teruya
kusumoto_teruya

Reputation: 2475

substitute for -indexPathsForRowsInRect: in UICollectionView

In UICollectionView, I'd like to get NSIndexPaths in the CGRect I define.
In the case of UITableView, there is the method -indexPathsForRowsInRect:.
But is there a substitute for the method in UICollectionView?

Upvotes: 1

Views: 263

Answers (2)

Ryan Heitner
Ryan Heitner

Reputation: 13632

A Swift version of Will Kiefer's answer

myCollectionView.collectionViewLayout.layoutAttributesForElements(in:myRect)!.map { $0.indexPath }

Upvotes: 0

Will Kiefer
Will Kiefer

Reputation: 31

You can get index paths for any given rect via the UICollectionViewLayout instance on every UICollectionView.

Calling -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect will give you an array of UICollectionViewLayoutAttributes objects, each of which will have the associated NSIndexPath.

Example category method:

@implementation UICollectionView (Example)

- (NSArray<NSIndexPath *> *)attributeIndexPathsForRect:(CGRect)rect {
    NSArray<UICollectionViewLayoutAttributes *> *allAttribs = [self.collectionViewLayout layoutAttributesForElementsInRect:rect];
    NSMutableArray<NSIndexPath *> *indexPaths = [[NSMutableArray alloc] init];
    for (UICollectionViewLayoutAttributes *attribs in allAttribs) {
        [indexPaths addObject:attribs.indexPath];
    }
    return indexPaths;
}

@end

Upvotes: 2

Related Questions