ios – 在UICollectionView中停止滚动

前端之家收集整理的这篇文章主要介绍了ios – 在UICollectionView中停止滚动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在浏览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中这些元素的属性.但是从那里开始,我不知道为什么他们会这样做.这种抵消调整来自何处?为什么要使用MAXFLOAT?任何想法将不胜感激.谢谢!

解决方法

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

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

猜你在找的iOS相关文章