【问题标题】:Get UICollectionView cell position after scrollToItemAtIndexPath在 scrollToItemAtIndexPath 之后获取 UICollectionView 单元格位置
【发布时间】:2014-05-11 15:02:33
【问题描述】:

我想在以编程方式滚动到一个单元格后获得UICollectionViewCell 的位置。我正在像这样设置滚动位置。

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

然后我想获取我滚动到的单元格的框架,因为我需要在它附近放置另一个 UIView

此代码使用滚动视图返回单元格的矩形,但我需要可见矩形内的位置。

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

【问题讨论】:

    标签: ios uikit uicollectionview


    【解决方案1】:

    单元格的框架不会改变,它是封闭滚动视图的内容偏移量。从帧的原点减去contentOffset 以获得屏幕上的位置,或使用convertRect: 方法之一获得相关视图中的坐标。

    【讨论】:

    • 谢谢。或者,是否有办法在设置滚动位置后立即获得对该单元格的引用? cellforitematindexpath 此时返回 nil。
    • 它返回 nil 因为单元格当时不在屏幕上。您现有的解决方案可能没问题。
    【解决方案2】:

    这是单元格 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      相关资源
      最近更新 更多