停止 UICollectionView 中的滚动

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);
}

我不明白他们试图做什么。唯一我理解的部分是创建目标矩形和获取目标矩形内元素的属性。但是从那里开始,我不知道他们为什么要这样做。这个offsetAdjustment是从哪里来的?为什么使用MAXFLOAT?如果您有任何想法,将不胜感激。谢谢!

1个回答

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

通过返回以此x量偏移的目标框架,滚动将捕捉到最近的单元格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接