Reputation: 2475
In UICollectionView
, I'd like to get NSIndexPath
s 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
Reputation: 13632
A Swift version of Will Kiefer's answer
myCollectionView.collectionViewLayout.layoutAttributesForElements(in:myRect)!.map { $0.indexPath }
Upvotes: 0
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