我已经customFlowLayout
在我的 iOS 应用程序中实现了。而且我已经将targetContentOffsetForProposedContentOffset:withScrollingVelocity
with subclassing 子类化了UICollectionViewFlowLayout
。现在我的问题是当用户滚动时,collectionview
它必须滚动到下一个索引。现在它随机滚动。
因此,任何人都知道如何使滚动限制为每个滚动仅一个项目。
以下是我的代码。
#pragma mark - UICollectionViewLayout (UISubclassingHooks)
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
CGSize collectionViewSize = self.collectionView.bounds.size;
CGFloat proposedContentOffsetCenterX = proposedContentOffset.x + collectionViewSize.width / 2;
CGRect proposedRect = CGRectMake(proposedContentOffset.x, 0, collectionViewSize.width, collectionViewSize.height);
UICollectionViewLayoutAttributes *candidateAttributes;
for (UICollectionViewLayoutAttributes *attributes in [self layoutAttributesForElementsInRect:proposedRect]) {
if (attributes.representedElementCategory != UICollectionElementCategoryCell) continue;
if (!candidateAttributes) {
candidateAttributes = attributes;
continue;
}
if (fabs(attributes.center.x - proposedContentOffsetCenterX) < fabs(candidateAttributes.center.x - proposedContentOffsetCenterX)) {
candidateAttributes = attributes;
}
}
proposedContentOffset.x = candidateAttributes.center.x - self.collectionView.bounds.size.width / 2;
CGFloat offset = proposedContentOffset.x - self.collectionView.contentOffset.x;
if ((velocity.x < 0 && offset > 0) || (velocity.x > 0 && offset < 0)) {
CGFloat pageWidth = self.itemSize.width + self.minimumLineSpacing;
proposedContentOffset.x += velocity.x > 0 ? pageWidth : -pageWidth;
}
return proposedContentOffset;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
if (!self.scaleItems) return [super layoutAttributesForElementsInRect:rect];
NSArray *attributesArray = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];
CGRect visibleRect = (CGRect){self.collectionView.contentOffset, self.collectionView.bounds.size};
CGFloat visibleCenterX = CGRectGetMidX(visibleRect);
[attributesArray enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *attributes, NSUInteger idx, BOOL *stop) {
CGFloat distanceFromCenter = visibleCenterX - attributes.center.x;
CGFloat absDistanceFromCenter = MIN(ABS(distanceFromCenter), self.scalingOffset);
CGFloat scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1;
attributes.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1);
}];
return attributesArray;
}