如何确定当前可见的UICollectionView单元格的indexPath

d_C*_*CFO 2 objective-c uicollectionview

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

最有帮助的是这些:

如何从UICollectionViewCell访问UICollectionView中Cell的indexPath

检测iOS UICollectionCell何时离开屏幕

较低的集合视图(self addSubview)包含可能的项目.较高的一个(self addSubview)包含较低的选项.用户按下按钮(再次自我addSubview),下部视图滚动到遗忘,上部视图展开,以便一个单元格填满屏幕.所有的阵列构建和显示都很好.没有*.nibs.

什么是行不通的是确定应用程序向用户呈现的单元格.

尝试#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);
}
Run Code Online (Sandbox Code Playgroud)

按照你的期望回应:

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]
Run Code Online (Sandbox Code Playgroud)

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

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

尝试#2:好的,好的.我将询问一个我知道当前可见细胞占据的点并从中推断出原因.

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

没有雪茄:

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

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

cellForItem indexPath < > 2 indexes [0, 2]
theCellsIndexPath=0
Run Code Online (Sandbox Code Playgroud)

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

尝试#3:也许我工作太辛苦了.我会陷入内心的事情

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath  {
}
Run Code Online (Sandbox Code Playgroud)

并滚动.

不.永远不会被召唤.

尝试#4:因为我不知道屏幕上单个单元格的indexPath(但是collectionView没有),我想我可以使用didEndDisplayingCell遍历所有单元格,直到我点击"Bingo!"这是粗略的并指示程序员错误.

我很高兴collectionView逻辑缓冲三个单元格.可能会改善用户体验或其他方面.但它最终结束 - 在0 - 不是我的数组索引最后知道它的位置 - 在2.

我没看过哪些文档?

Q8i*_*Q8i 12

我没看过哪些文档?

UICollectionView有一个叫做的方法indexPathsForVisibleItems.请务必仔细阅读以了解API中可以使用的其他内容.