【问题标题】:How to determine indexPath of currently visible UICollectionView cell如何确定当前可见 UICollectionView 单元格的 indexPath
【发布时间】:2013-09-03 18:05:46
【问题描述】:

我想显示一些特定于单元格的文本,但我无法从集合视图中取出可见单元格。

最有帮助的是这些:

how to access from UICollectionViewCell the indexPath of the Cell in UICollectionView

detecting when an iOS UICollectionCell is going off screen

较低的集合视图(self addSubview)包含可能的项目。一个上层(self addSubview)包含来自下层的选择。用户按下一个按钮(再次自我 addSubview),下部视图滚动到遗忘,上部视图展开,使得一个单元格填满屏幕。所有的阵列构建和显示工作正常。没有 *.nib。

无法确定应用向用户呈现的是哪个单元格。

尝试 #1:首先,我尝试将 UILabel 与正常操作并行填充。按下按钮和 cellForItemAtIndexPath:

if (cv.tag == UPPER_CV_TAG) {
    UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    NSIndexPath *tempIndexPath;
tempIndexPath = itemAttributes.indexPath;
NSLog(@"cellForItem indexPath %@",indexPath);
NSLog(@"layout indexPath %@",tempIndexPath);
}

如您所愿地响应:

cellForItem indexPath <blah blah> 2 indexes [0, 0]
layout indexPath < > 2 indexes [0, 0]

cellForItem indexPath < > 2 indexes [0, 1]
layout indexPath < > 2 indexes [0, 1]

cellForItem indexPath < > 2 indexes [0, 2]
layout indexPath < > 2 indexes [0, 2]

当旋转结束时,单元 0 正确地占据了中心舞台。不幸的是,单元格 2 的描述也是如此。向左/向右滚动,单元格会相应更改,相应的文本不会。它保持不变:映射到单元格 2 的那个。

显然我将错误的索引传递给描述数组。

尝试 #2:好的,好的。我将询问一个我知道当前可见单元格占据的点,并据此进行推理。

CGPoint p = CGPointMake(512, 456);
NSIndexPath *theCellsIndexPath = [self.upper_collectionView indexPathForItemAtPoint:p];
NSLog(@"theCellsIndexPath=%d",theCellsIndexPath.item);

没有雪茄:

cellForItem indexPath < > 2 indexes [0, 0]
theCellsIndexPath=0

cellForItem indexPath < > 2 indexes [0, 1]
theCellsIndexPath=0

cellForItem indexPath < > 2 indexes [0, 2]
theCellsIndexPath=0

当我将 512,456 更改为其他可能的点时,从“0”没有变化。当我使用 layoutAttributes 来确定单元格在视图中的位置时,从“0”没有变化,以防万一。不,那个细胞是一个非常非常大的目标。我没有错过它。

尝试#3:也许我工作太努力了。我会把事情的进展困在里面

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath  {
}

并顺其自然。

不。它永远不会被调用。

尝试 #4:由于我不知道屏幕上单个单元格的 indexPath(但 collectionView 知道),我想我可以使用 didEndDisplayingCell 遍历所有单元格,直到我点击“Bingo!”这是粗略的,表明程序员有错误。

我很高兴 collectionView 逻辑缓冲了三个单元格。可能会改善用户体验或其他东西。但它最终的位置——在 0 上——并不是我的数组索引最后知道的位置——在 2。

我没有阅读文档的哪些部分?

【问题讨论】:

  • indexPathForCell: 不起作用?
  • [UICollectionView indexPathsForVisibleItems] 不适合你吗?

标签: objective-c uicollectionview


【解决方案1】:

我没有阅读文档的哪些部分?

UICollectionView 有一个名为 indexPathsForVisibleItems 的方法。请务必通读它以了解您还可以从 API 中使用什么。

【讨论】:

    【解决方案2】:

    试试collectionView.visibleCells

    NSArray *ary = collectionView.visibleCells;
    for (UICollectionViewCell *cell in ary) {
        NSIndexPath *path = [collectionView indexPathForCell:cell];
        NSLog(@"indexPath of cell: Section: %d , Row: %d", (int)path.section, (int)path.row);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多