UICollectionView indexPathsForVisibleItems顺序

时间:2014-01-13 07:33:36

标签: ios objective-c uicollectionview

我使用UICollectionView显示第2列中的内容。我需要跟踪可见单元格中的更改。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray* visibleCellIndex = collectionViewCatalog.indexPathsForVisibleItems;

    NSIndexPath* newFirstVisibleCell = [visibleCellIndex firstObject];
    NSIndexPath* newLastVisibleCell = [visibleCellIndex lastObject];
    NSLog(@"Visible cells [ %i ; %i]",newFirstVisibleCell.row,newLastVisibleCell.row);
}

记录:Visible cells [ 0 ; 3],但有时崩溃顺序Visible cells [ 5 ; 4]Visible cells [ 12 ; 11] 记录单元格的indexPathsForVisibleItems [5; 4]:

(
    "<NSIndexPath: 0x1653bb90> {length = 2, path = 0 - 5}",
    "<NSIndexPath: 0x1655ab10> {length = 2, path = 0 - 2}",
    "<NSIndexPath: 0x1655aa80> {length = 2, path = 0 - 3}",
    "<NSIndexPath: 0x16539680> {length = 2, path = 0 - 4}"
)

此后(可见细胞[5; 4])下一个日志信息:Visible cells [ 6 ; 9]没有从5到9个细胞的记录

我只有20个细胞。为什么在数组indexPathsForVisibleItems中崩溃顺序indexPath?

2 个答案:

答案 0 :(得分:12)

来自NSIndexPath标头:

// comparison support
- (NSComparisonResult)compare:(NSIndexPath *)otherObject; // sorting an array of indexPaths using this comparison results in an array representing nodes in depth-first traversal order

你可以这么做:

NSArray *sortedVisibleItems = [[collectionViewCatalog indexPathsForVisibleItems] sortedArrayUsingSelector:@selector(compare:)];

答案 1 :(得分:3)

NSArray *sortedIndexPaths = [visibleCellIndex sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSIndexPath *path1 = (NSIndexPath *)obj1;
            NSIndexPath *path2 = (NSIndexPath *)obj2;
            return [path1 compare:path2];
        }];