gpt4 book ai didi

ios - 带分页的 UICollectionView - 设置页面宽度

转载 作者:IT王子 更新时间:2023-10-29 08:01:55 38 4
gpt4 key购买 nike

我有一个可以一次显示大约 3.5 个单元格的 Collection View ,我希望它可以分页。但我希望它捕捉到每个单元格(就像 App Store 应用程序一样),而不是 ScrollView 的整个宽度。我该怎么做?

最佳答案

另一种方法是创建一个自定义的 UICollectionViewFlowLayout 并重写方法,如下所示:

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)offset 
withScrollingVelocity:(CGPoint)velocity {

CGRect cvBounds = self.collectionView.bounds;
CGFloat halfWidth = cvBounds.size.width * 0.5f;
CGFloat proposedContentOffsetCenterX = offset.x + halfWidth;

NSArray* attributesArray = [self layoutAttributesForElementsInRect:cvBounds];

UICollectionViewLayoutAttributes* candidateAttributes;
for (UICollectionViewLayoutAttributes* attributes in attributesArray) {

// == Skip comparison with non-cell items (headers and footers) == //
if (attributes.representedElementCategory !=
UICollectionElementCategoryCell) {
continue;
}

// == First time in the loop == //
if(!candidateAttributes) {
candidateAttributes = attributes;
continue;
}

if (fabsf(attributes.center.x - proposedContentOffsetCenterX) <
fabsf(candidateAttributes.center.x - proposedContentOffsetCenterX)) {
candidateAttributes = attributes;
}
}

return CGPointMake(candidateAttributes.center.x - halfWidth, offset.y);

}

如果您正在寻找 Swift 解决方案,请查看此 Gist

  • 注意:当我们真正显示预览单元格时(即使它们的 alpha 为 0.0f),这将起作用。这是因为如果预览单元格在滚动时不可用,它们的属性对象将不会在循环中传递...

关于ios - 带分页的 UICollectionView - 设置页面宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20496850/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com