UICollectionView 不规则布局实践

最近在优化不规则布局排版,之前项目中不规则布局排版一直用的button布局形式,后面一个button的frame根据前一个已经布局好的frame计算而来,类似于用js实现的布局流效果。最近在考虑用collectionView来实现这块,布局后的效果如下:


未命名.gif

简单说下CollectionViewLayout,它是负责collectionView的布局类,所有的布局信息由它负责。每一个UICollectionViewLayoutAttributes对应着一个collectionView元素,包括UICollectionViewCell、Supplementary Views 追加视图 (类似于UITableViewHeader或者Footer)、和Decoration Views 装饰视图 (用作背景展示),查看Apple开发文档UICollectionViewLayoutAttributes属性,可以实现诸如frame、size、transform3D、alpha、zIndex(多个CollectionView元素重叠时,可以用此调整显示的顺序)、representedElementCategory(暂时没研究)和representedElementCategory(暂时没研究),上面的效果实现主要用到frame定位,frame也是自定义layout用得最多的layout属性。

下面以实现上面效果为例,上代码
自定义layout类的.h文件

#import <UIKit/UIKit.h>
@class HHIrregularLayout;

@protocol HHIrregularLayoutDataSource <NSObject>

/**
 获取section的大小
 */
- (CGSize)layout:(HHIrregularLayout *)collectionViewLayout sizeForSectionAtIndexPath:(NSIndexPath *)indexPath;

/**
 获取item的大小
 */
- (CGSize)layout:(HHIrregularLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

@end



@interface HHIrregularLayout : UICollectionViewLayout

@property (assign, nonatomic) CGFloat rowSpacing;//行间距
@property (assign, nonatomic) CGFloat columnSpacing;//列间距
@property (assign, nonatomic) id<HHIrregularLayoutDataSource> dataSource;

@end

.h文件主要是定义了HHIrregularLayoutDataSource,用来获取section和每个item的大小信息,以及item的行间距和列间距
接下来,我们看.m文件
首先定义延展,用来记录所有的item的frame 和 section的frame 和 所有的属性atts

@interface HHIrregularLayout ()

@property (strong, nonatomic) NSMutableArray *itemFrames;//可能为二维数组(当为多个section时) 或一维数组(当为1个section时)
@property (strong, nonatomic) NSMutableArray *sectionFrames;
@property (strong, nonatomic) NSMutableArray *atts;

@end

下面的init方法只会在alloc时调用,可以在里面初始化一些默认值

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //设置默认数据
        self.rowSpacing = 0;
        self.columnSpacing = 0;
    }
    return self;
}

懒加载部分如下

- (NSMutableArray *)sectionFrames
{
    if (!_sectionFrames) {
        _sectionFrames = [NSMutableArray array];
    }
    return _sectionFrames;
}


- (NSMutableArray *)itemFrames
{
    if (!_itemFrames) {
        _itemFrames = [NSMutableArray array];
    }
    return _itemFrames;
}

- (NSMutableArray *)atts
{
    if (!_atts) {
        _atts = [NSMutableArray array];
    }
    return _atts;
}

prepareLayout方法用来布局的准备,每次layout变化时都会重新调用,这里主要做每个元素item的计算等

- (void)prepareLayout
{
    [super prepareLayout];
    [self setUpItemsFrames];
}


- (void)setUpItemsFrames
{
    [self.sectionFrames removeAllObjects];
    [self.itemFrames removeAllObjects];
    [self.atts removeAllObjects];
    
    int sectionCount = [self.collectionView numberOfSections];
    
    for (int sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
        
        NSIndexPath *sectionIndexPath = [NSIndexPath indexPathForItem:0 inSection:sectionCount];
        int itemCount = [self.collectionView numberOfItemsInSection:sectionIndex];

        CGFloat sectionHeight = [self.dataSource layout:self sizeForSectionAtIndexPath:sectionIndexPath].height;
        
        if (sectionIndex == 0) {
            
            CGRect sectionFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, sectionHeight);
            [self.sectionFrames addObject:NSStringFromCGRect(sectionFrame)];
        }
        else {
            int lastItemCount = [self.collectionView numberOfItemsInSection:sectionIndex -1];

            CGRect lastItemFrame = CGRectFromString(self.itemFrames[sectionIndex - 1][lastItemCount -1]);
            CGRect sectionFrame = CGRectMake(0, CGRectGetMaxY(lastItemFrame), [UIScreen mainScreen].bounds.size.width, sectionHeight);
            [self.sectionFrames addObject:NSStringFromCGRect(sectionFrame)];
        }
        
        
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForRow:0 inSection:sectionIndex]];
        att.frame = CGRectFromString(self.sectionFrames[sectionIndex]);
        [self.atts addObject:att];
        
        NSMutableArray *mutableArr = [NSMutableArray array];
        
        for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) {
            
            CGSize size = [self.dataSource layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForItem:itemIndex inSection:sectionIndex]];
            
            if (itemIndex == 0) {
                CGRect sectionFrame = CGRectFromString(self.sectionFrames[sectionIndex]);
                [mutableArr addObject:NSStringFromCGRect(CGRectMake(0, CGRectGetMaxY(sectionFrame), size.width, size.height))];
            }
            else {
                
                CGRect lastFrame = CGRectFromString(mutableArr[itemIndex -1]);
                if (CGRectGetMaxX(lastFrame) + self.columnSpacing + size.width < [UIScreen mainScreen].bounds.size.width) {
                    [mutableArr addObject:NSStringFromCGRect(CGRectMake(CGRectGetMaxX(lastFrame) + self.columnSpacing, CGRectGetMinY(lastFrame), size.width, size.height))];
                }
                else {
                    [mutableArr addObject:NSStringFromCGRect(CGRectMake(0, CGRectGetMaxY(lastFrame) + self.rowSpacing, size.width, size.height))];
                }
            }
            
            UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:itemIndex inSection:sectionIndex]];
            att.frame = CGRectFromString(mutableArr[itemIndex]);
            [self.atts addObject:att];
        }
        [self.itemFrames addObject:mutableArr];
    }
}

-- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds布局对象信息发生改变时是否需要重新局部,建议return YES;

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

下面返回CollectionView的ContentSize

- (CGSize)collectionViewContentSize
{
    NSMutableArray *frames = self.itemFrames.lastObject;
    CGFloat lastItemMaxY = CGRectGetMaxY(CGRectFromString(frames.lastObject));
    return CGSizeMake(0, lastItemMaxY > self.collectionView.bounds.size.height ? lastItemMaxY:self.collectionView.bounds.size.height + 1);
}

(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect返回所有的元素的layout属性,包括Supplementary Views和Decoration Views

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.atts;
}

下面两个方法分别返回Supplementary Views和Decoration Views布局信息

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"section:%ld", (long)indexPath.section);
    UICollectionViewLayoutAttributes *headerAtts = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
    headerAtts.frame = CGRectFromString(self.sectionFrames[indexPath.section]);
    return headerAtts;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"section:%ld item:%ld", (long)indexPath.section, (long)indexPath.item);
    UICollectionViewLayoutAttributes *itemAtts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    itemAtts.frame = CGRectFromString(self.itemFrames[indexPath.section][indexPath.item]);
    return itemAtts;
}

转载请注明出处,谢谢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容