ios – 如何在UICollectionView中垂直对齐UICollectionViewCells?

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

解决方法

我将提供的UICollectionViewFlowLayout扩展到了我的UICollectionView.以下压倒一切对我有用.
#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,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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...