替换-indexPathsForRowsInRect:在UICollectionView中

时间:2015-04-24 01:47:38

标签: objective-c uicollectionview

UICollectionView中,我希望在我定义的CGRect中获得NSIndexPath
UITableView的情况下,方法为-indexPathsForRowsInRect: 但在UICollectionView

中是否可以替代该方法

2 个答案:

答案 0 :(得分:2)

您可以通过每个UICollectionViewLayout上的UICollectionView实例获取任何指定rect的索引路径。

调用-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect将为您提供一系列UICollectionViewLayoutAttributes个对象,每个对象都有关联的NSIndexPath

示例类别方法:

@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

答案 1 :(得分:0)

Will Kiefer答案的Swift版本

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