简体   繁体   English

在scrollToItemAtIndexPath之后获取UICollectionView单元格位置

[英]Get UICollectionView cell position after scrollToItemAtIndexPath

I would like to get a UICollectionViewCell 's position after programattically scrolling to a cell. 我想以编程方式滚动到单元格后得到UICollectionViewCell的位置。 I'm setting the scroll position like this. 我正在这样设置滚动位置。

[self.collectionView scrollToItemAtIndexPath:indexPath
                             atScrollPosition:UICollectionViewScrollPositionCenteredVertically
                                        animated:NO];

I would then like to get the frame of the cell I have scrolled to as I need to position another UIView near it. 然后,我想获取已滚动到的单元格的框架,因为需要在其附近UIView另一个UIView

This code returns the rect of the cell with the scrollview, but I need the position within the visible rect. 这段代码返回带有滚动视图的单元格的矩形,但是我需要在可见矩形内定位。

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellRect = attributes.frame;

The frame of a cell doesn't change, it's the content offset of the enclosing scroll view. 单元格的框架不变,它是封闭滚动视图的内容偏移量。 Subtract the contentOffset from the frame's origin to get the on-screen position, or use one of the convertRect: methods to get the coordinates in a related view. 从帧的原点减去contentOffset以获得屏幕上的位置,或使用convertRect:方法之一获取相关视图中的坐标。

Here is the cell X and Center values 这是单元格X和中心值

UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGPoint cellCenterPoint = attributes.center;
CGPoint contentOffset = [collectionView contentOffset];
NSLog(@"%f  , %f",-1*contentOffset.x , cellCenterPoint.x);
int  relativeCellCenter = (-1*contentOffset.x) + cellCenterPoint.x +collectionView.frame.origin.x;
int relativeX = (-1*contentOffset.x) +collectionView.frame.origin.x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM