UICollectionView的灵活布局 --从一个需求谈起

最近想把自己搞的一些东西写出来,刚把之前文章的排版整理了整理,以后一定要坚持更新简书了。

那么这篇文章来了,一切的起源在于一个这样的布局需求。


Simulator Screen Shot 2015年11月27日 下午11.13.27.png

首先就想到collectionView。用tableView也能强行实现就是了,但是比较笨重,改动布局就得重画cell,所以本文就详细介绍下我怎么实现这个需求的。


此处先放点新手福利

如果你没接触过UICollectionView,但对UITableView比较熟悉的,可以看下这段,熟悉UICollectionView可以直接跳过。连UITableView都不熟的建议从基础开始学。

绘制UICollectionView类似于UITableView,满足delegate和dataSouce两个代理。

注意的区别是:
1、UICollectionView的indexPath,通常使用item的属性,印象中row的属性跟UITableView不一样,和section毫无关系。
2、每个section的head和footViewz在这个代理里实现。

 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

这个view可以像cell一样复用的。在初始化时注册:

 [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];

使用时:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { 
   UICollectionReusableView *reusableview = nil;
   if (kind == UICollectionElementKindSectionHeader) {
       UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader" forIndexPath:indexPath];
       headerView.backgroundColor = [UIColor redColor];
       reusableview = headerView;
}
return reusableview;

3、UICollectionView的cell选中的时候是有backgroundView和selectedBackgroundView两个属性的,可以做出一些选择效果:

@property (nonatomic, strong, nullable) UIView *backgroundView;
@property (nonatomic, strong, nullable) UIView *selectedBackgroundView;

4、每个UICollectionView初始化都要有个UICollectionViewLayout来实现布局,用系统自带的布局UICollectionViewDelegateFlowLayout的话,满足这个代理设置高度:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

UICollectionViewDelegateFlowLayout里还有好几个参数和其他的代理,有兴趣的同学可以去看看api,然后写个demo测试一下,因为蛮简单的,这里就不再深究了。。

新手福利结束


回归正题

现在回到我我们的需求上。

满足这个需求我们必须重写UICollectionViewLayout。

核心重写的方法如下:

//每次布局都会调用
- (void)prepareLayout;
//布局完成后设置contentSize
- (CGSize)collectionViewContentSize;
//返回每个item的属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
//返回所有item属性
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 

当然最重要的是,你的一些参数得通过代理或者Block传出来赋值。

/*
*  获取item宽高
*
*  @param block 返回宽高的block
*/
- (void)calculateItemSizeWithWidthBlock:(CGSize (^)(NSIndexPath *indexPath))block;

下面是代码,注释丰富,可以放心阅读:

HomeCollectionLayout.h:

typedef CGSize(^SizeBlock)(NSIndexPath *indexPath);

@interface HomeCollectionLayout : UICollectionViewLayout

/** 行间距 */
@property (nonatomic, assign) CGFloat rowSpacing;
/** 列间距 */
@property (nonatomic, assign) CGFloat lineSpacing;
/** 内边距 */
@property (nonatomic, assign) UIEdgeInsets sectionInset;

/*
*  获取item宽高
*
*  @param block 返回宽高的block
*/
- (void)calculateItemSizeWithWidthBlock:(CGSize (^)(NSIndexPath *indexPath))block;

HomeCollectionLayout.m

@interface HomeCollectionLayout()
/** 计算每个item高度的block,必须实现*/
@property (nonatomic, copy) SizeBlock block;

/** 存放元素高宽的键值对 */
@property (nonatomic, strong) NSMutableArray *arrOfSize;
/**存放所有item的attrubutes属性 */
@property (nonatomic, strong) NSMutableArray *array;
/**存放所有section的高度的 */
@property (nonatomic, strong) NSMutableArray *arrOfSectionHeight;

/**总section高度,用于直接输出contentSize */
@property (nonatomic,assign) CGFloat collectionSizeHeight;
/**总共item个数 */
@property (nonatomic,assign) NSInteger itemCount;

@property (nonatomic,assign) CGFloat collectionWidth;

@end

@implementation HomeCollectionLayout
- (instancetype)init
{
    self = [super init];
    if (self) {
        //对默认属性进行设置
        _arrOfSize = [NSMutableArray array];
        _array = [NSMutableArray array];
        _arrOfSectionHeight = [NSMutableArray array];
        
        self.itemCount = 0;
    
        self.collectionSizeHeight = 0;
        
        self.sectionInset = UIEdgeInsetsMake(2, 0, 0, 0);
        
        self.lineSpacing = 1;
        self.rowSpacing = 1;
    }
    return self;
}

/**
 *  准备好布局时调用
 */
- (void)prepareLayout {
    [super prepareLayout];

    //reload的时候清空原有数据
    [_array removeAllObjects];
    [_arrOfSize removeAllObjects];
    [_arrOfSectionHeight removeAllObjects];
    _collectionSizeHeight = 0;
    _itemCount = 0;

    NSInteger sectionCount = [self.collectionView numberOfSections];
    //根据每个indexPath储存
    for (NSInteger i = 0 ; i < sectionCount; i++) {
        NSInteger rowCount = [self.collectionView numberOfItemsInSection:i];
        //存储item的总数目
        self.itemCount += rowCount;
        //存储每个列数的长度
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       
        //计算该section列数
        NSInteger lines = 0;
        CGSize size = CGSizeZero;
        if (self.block != nil) {
            size = self.block([NSIndexPath indexPathForRow:0 inSection:i]);
        }else{
            NSAssert(size.width != 0 ,@"未实现block");
        }
        lines = self.collectionWidth/size.width;
        
        //存储每个列数的长度
        for (NSInteger k = 0; k < lines; k++) {
            [dict setObject:@(self.sectionInset.top) forKey:[NSString stringWithFormat:@"%ld",(long)k]];
        }
        [_arrOfSize addObject:dict];
        
        for (NSInteger j = 0; j < rowCount; j++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            //调用item计算。
            [_array addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
        }
        
        //此时dict已经改变
        NSMutableDictionary *mdict = _arrOfSize[i];
        //计算每个section的高度
        __block NSString *maxHeightline = @"0";
        [mdict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *obj, BOOL *stop) {
            if ([mdict[maxHeightline] floatValue] < [obj floatValue] ) {
                maxHeightline = key;
            }
        }];
        [self.arrOfSectionHeight addObject:mdict[maxHeightline]];
        self.collectionSizeHeight += [mdict[maxHeightline] floatValue];
        
        NSLog(@"\ncontentSize = %@ height = %f\n\n",NSStringFromCGSize(CGSizeMake(self.collectionView.bounds.size.width, self.collectionSizeHeight)),[mdict[maxHeightline] floatValue]);
    }
}
/**
 *  设置可滚动区域范围
 */
- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.collectionView.bounds.size.width, self.collectionSizeHeight);
}
/**
 *  计算indexPath下item的属性的方法
 *
 *  @return item的属性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //创建item的属性
    UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGSize size = CGSizeZero;
    if (self.block != nil) {
        size = self.block(indexPath);
    }else{
        NSAssert(size.width != 0 ,@"未实现block");
    }
    CGRect frame;
    frame.size = size;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[_arrOfSize objectAtIndex:indexPath.section]];
    //循环遍历找出高度最短行
    __block NSString *lineMinHeight = @"0";
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *obj, BOOL *stop) {
        if ([dict[lineMinHeight] floatValue] > [obj floatValue]) {
            lineMinHeight = key;
        }
    }];
    int line = [lineMinHeight intValue];
    
    
    //找出最短行后,计算item位置
    frame.origin = CGPointMake(line * (size.width + self.lineSpacing), [dict[lineMinHeight] floatValue] + self.collectionSizeHeight);
    dict[lineMinHeight] = @(frame.size.height + self.rowSpacing + [dict[lineMinHeight] floatValue]);
    //存储高度
    [_arrOfSize replaceObjectAtIndex:indexPath.section withObject:dict];
    attr.frame = frame;
    
    NSLog(@"\nframe = %@,indexPath = %@\n\n",NSStringFromCGRect(frame),indexPath);
    
    
    
    return attr;
}
/**
 *  返回视图框内item的属性,可以直接返回所有item属性
 */
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _array;
}

#pragma mark - data source

/**
 *  设置计算高度block方法
 *
 *  @param block 计算item高度的block
 */
- (void)calculateItemSizeWithWidthBlock:(CGSize (^)(NSIndexPath *indexPath))block {
    if (self.block != block) {
        self.block = block;
    }
}

#pragma mark - getter & setter
- (CGFloat)collectionWidth {
    return self.collectionView.frame.size.width;
}
@end

demo地址:本文demo

小结:跟一般瀑布流不同,这种布局collectionItem的size全部要自己定制,比起强行画来说,这么做以后更好改。就是算死我了,算法还是需要加强。

另外,这里另外一名作者Tuberose写了篇更详细的关于瀑布流的文章:

想更深入研究的同学可以移步这里:瀑布流小框架


简书已经弃用,欢迎移步我的小专栏:
https://xiaozhuanlan.com/dahuihuiiOS

写文不易,大家看到了顺手点个喜欢呗~ 也让我更有动力分享些东西,谢谢啦~

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

推荐阅读更多精彩内容