美文网首页
UICollectionView中,indexPathsForV

UICollectionView中,indexPathsForV

作者: 左方 | 来源:发表于2023-04-22 13:21 被阅读0次

self.collectionView.indexPathsForVisibleItems是一个包含了当前可见的所有cell的indexPath的数组,但它并不一定是按照显示顺序排列的,因为UICollectionView的cell可以以任意的顺序被加载和显示。
例如,在UICollectionView中,如果用户快速滑动,会出现这样的情况:先加载在后面的cell,然后再加载在前面的cell,这样就会导致self.collectionView.indexPathsForVisibleItems数组的顺序与显示顺序不一致。

如果需要按照显示顺序来处理可见的cell,可以使用visibleCells属性获取所有可见的cell,并按照它们在UICollectionView中的位置来排序。例如,可以使用以下代码对可见的cell按照它们在UICollectionView中的位置进行排序:

NSArray *visibleCells = [self.collectionView visibleCells];
NSArray *sortedCells = [visibleCells sortedArrayUsingComparator:^NSComparisonResult(UICollectionViewCell *cell1, UICollectionViewCell *cell2) {
    NSIndexPath *indexPath1 = [self.collectionView indexPathForCell:cell1];
    NSIndexPath *indexPath2 = [self.collectionView indexPathForCell:cell2];
    return [indexPath1 compare:indexPath2];
}];

或者:

NSArray *visibleIndexPaths = self.collectionView.indexPathsForVisibleItems;
NSArray *sortedIndexPaths = [visibleIndexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *indexPath1, NSIndexPath *indexPath2) {
        return [indexPath1 compare:indexPath2];
    }];

相关文章

网友评论

      本文标题:UICollectionView中,indexPathsForV

      本文链接:https://www.haomeiwen.com/subject/coysjdtx.html