5

我正在浏览 Apple 的 UICollectionView 示例代码,我想知道是否有人可以向我解释一些事情。他们使用此代码来停止集合视图中的水平滚动:

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    CGFloat offsetAdjustment = MAXFLOAT;
    CGFloat horizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);

    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    NSArray* array = [super layoutAttributesForElementsInRect:targetRect];

    for (UICollectionViewLayoutAttributes* layoutAttributes in array) {
        CGFloat itemHorizontalCenter = layoutAttributes.center.x;

        if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) {
            offsetAdjustment = itemHorizontalCenter - horizontalCenter;
        }
    }    
    return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}

我不明白他们想要做什么。我理解的唯一部分是创建 targetRect 并获取 targetRect 中这些元素的属性。但从那里开始,我不知道他们为什么要这么做。这个 offsetAdjustment 是从哪里来的?为什么使用 MAXFLOAT?任何想法将不胜感激。谢谢!

4

1 回答 1

3

代码的目的是调整滚动结束位置,使其“捕捉”到特定的单元格。这是通过offsetAdjustment. MAXFLOAT只是初始值;循环offsetAdjustment内迭代地减小到目标框架中心与最靠近目标框架中间的单元格之间的水平距离。

通过返回这个 x 量的目标帧偏移量,滚动将捕捉到这个最近的单元格。

于 2012-12-28T01:15:41.597 回答