I’m going through Apple’s sample code for UICollectionView and I was wondering if someone could explain something to me. They use this code to stop the horizontal scrolling in a collection view:
- (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);
}
I don’t get what they are trying to do. The only part I understand, is creating the targetRect and getting the attributes for those elements in the targetRect. But from there, I don’t know why they do what they do. Where this offsetAdjustment comes from? Why use MAXFLOAT? Any thoughts would be greatly appreciated. Thanks!
The purpose of the code is to adjust the scrolling end position so it ‘snaps’ to a particular cell. This is done with the
offsetAdjustment.MAXFLOATis just the initial value; within the loopoffsetAdjustmentis iteratively decreased to the horizontal distance between the centres of the target frame and the cell closest to the middle of the target frame.By returning the target frame offset by this x amount, scrolling will snap to this closest cell.