gpt4 book ai didi

ios - 如何垂直对齐 UICollectionView 中的 UICollectionViewCells?

转载 作者:可可西里 更新时间:2023-11-01 03:06:00 26 4
gpt4 key购买 nike

我在水平滚动的 UICollectionView 上有不同高度的单元格,它似乎垂直均匀地分布单元格,在单元格之间留下空白空间,我想顶部对齐它们并有可变的空白空间在每列的底部。

最佳答案

我扩展了提供给 UICollectionView 的 UICollectionViewFlowLayout。以下重写对我有用。

#import "TopAlignedCollectionViewFlowLayout.h"

const NSInteger kVerticalSpacing = 10;

@implementation TopAlignedCollectionViewFlowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {
if (nil == attributes.representedElementKind) {
NSIndexPath* indexPath = attributes.indexPath;
attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
}
}
return attributesToReturn;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes* currentItemAttributes =
[super layoutAttributesForItemAtIndexPath:indexPath];
UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout sectionInset];
if (indexPath.item == 0) {
CGRect frame = currentItemAttributes.frame;
frame.origin.y = sectionInset.top;
currentItemAttributes.frame = frame;

return currentItemAttributes;
}
NSIndexPath* previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section];
CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame;
CGFloat previousFrameRightPoint = previousFrame.origin.y + previousFrame.size.height + kVerticalSpacing;
CGRect currentFrame = currentItemAttributes.frame;
CGRect strecthedCurrentFrame = CGRectMake(currentFrame.origin.x,
0,
currentFrame.size.width,
self.collectionView.frame.size.height
);
if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) {
CGRect frame = currentItemAttributes.frame;
frame.origin.y = frame.origin.y = sectionInset.top;
currentItemAttributes.frame = frame;
return currentItemAttributes;
}
CGRect frame = currentItemAttributes.frame;
frame.origin.y = previousFrameRightPoint;
currentItemAttributes.frame = frame;
return currentItemAttributes;
}

@end

关于ios - 如何垂直对齐 UICollectionView 中的 UICollectionViewCells?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17033194/

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