iOS-Autolayout自动计算itemSize的UICollectionViewLayout瀑布流布局

UICollectionViewLayout基础知识

Custom Layout

官方描述
An abstract base class for generating layout information for a collection view
The job of a layout object is to determine the placement of cells, supplementary views, and decoration views inside the collection view’s bounds and to report that information to the collection view when asked

官方文档

UICollectionViewLayout的功能为向UICollectionView提供布局信息,不仅包括cell布局信息,也包括追加视图装饰视图的布局信息。实现一个自定义Custom Layout的常规做法是继承UICollectionViewLayout

重载的方法

  • prepareLayout:准备布局属性
  • layoutAttributesForElementsInRect:返回rect中的所有的元素的布局属性UICollectionViewLayoutAttributes可以是cell追加视图装饰视图的信息,通过不同的UICollectionViewLayoutAttributes初始化方法可以得到不同类型的UICollectionViewLayoutAttributes
  • layoutAttributesForCellWithIndexPath:
  • layoutAttributesForSupplementaryViewOfKind:withIndexPath:
  • layoutAttributesForDecorationViewOfKind:withIndexPath:
  • collectionViewContentSize返回contentSize

执行顺序

  1. -(void)prepareLayout将被调用,默认下该方法什么没做,但是在自己的子类实现中,一般在该方法中设定一些必要的layout的结构和初始需要的参数等
  2. -(CGSize) collectionViewContentSize将被调用,以确定collection应该占据的尺寸。注意这里的尺寸不是指可视部分的尺寸,而应该是所有内容所占的尺寸。collectionView的本质是一个scrollView,因此需要这个尺寸来配置滚动行为
  3. -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

引入AutoLayout自动计算的瀑布流

关于瀑布流

网上前辈们已经写烂了,这里只简述:

  • -(void)prepareLayout中:就是通过一个记录列高度的数组(或字典),在创建LayoutAttributes的frame时确定当前最短列,根据外部传入的相关的spacingcollectionViewinset属性,确定宽度frame等信息,存入Attributes的数组。
  • -(CGSize) collectionViewContentSize中:通过列高度数组很容易确定当前范围,contentSize不等于collectionview的bounds.size,计算时留意一下
  • -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:返回第一步中计算获得的Attributes数组即可

以上可以帮助我们实现一个瀑布流的效果,但是离实际应用还有一段差距。

分析:
实际应用中,我们的网络请求是会有一个pageSize的,而且列表的赋值通常是直接进行数据源的赋值然后reloadData。所以数据源个数等于pageSize时,我们认为是刷新,大于时,则为分页加载。
根据这套逻辑,这里将pageSizedataSource作为属性引入到Custom Layout中,同时维护一个记录计算结果的数组itemSizeArray,提高计算效率,具体代码如下:

- (void)calculateAttributesWithItemWidth:(CGFloat)itemWidth{
    BOOL isRefresh = self.datas.count <= self.pageSize;
    if (isRefresh) {
        [self refreshLayoutCache];
    }
    NSInteger cacheCount = self.itemSizeArray.count;
    for (NSInteger i = cacheCount; i < self.datas.count; i ++) {
        CGSize itemSize = [self calculateItemSizeWithIndex:i];
        UICollectionViewLayoutAttributes *layoutAttributes = [self createLayoutAttributesWithItemSize:itemSize index:i];
        [self.itemSizeArray addObject:[NSValue valueWithCGSize:itemSize]];
        [self.layoutAttributesArray addObject:layoutAttributes];
    }
}
- (UICollectionViewLayoutAttributes *)createLayoutAttributesWithItemSize:(CGSize)itemSize index:(NSInteger)index{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    struct SPColumnInfo shortestInfo = [self shortestColumn:self.columnHeightArray];
    // x
    CGFloat itemX = (self.itemWidth + self.interitemSpacing) * shortestInfo.columnNumber;
    // y
    CGFloat itemY = self.columnHeightArray[shortestInfo.columnNumber].floatValue + self.lineSpacing;
    // size
    layoutAttributes.frame = (CGRect){CGPointMake(itemX, itemY),itemSize};
    self.columnHeightArray[shortestInfo.columnNumber] = @(CGRectGetMaxY(layoutAttributes.frame));
    return layoutAttributes;
}
- (void)refreshLayoutCache{
    [self.layoutAttributesArray removeAllObjects];
    [self.columnHeightArray removeAllObjects];
    [self.itemSizeArray removeAllObjects];
    for (NSInteger index = 0; index < self.columnNumber; index ++) {
        [self.columnHeightArray addObject:@(self.viewInset.top)];
    }
}

代码里可以看到,itemSizeArray的属性,用于记录自动计算的itemSize,通过这个属性可以帮助我们减少不必要的重复计算

关于自动计算

注意

  • Self-size要求我们的约束自上而下设置,确保能够通过Constraint计算获得准确的高度。具体不再赘述
  • 本Demo仅适用图片比例确定的瀑布流,如果需求是图片size自适应,需要服务器返回能够计算的必要参数

自动计算的思路,类似UITableView-FDTemplateLayoutCell,通过xibNameclassName初始化一个template cell注入数据并添加横向约束后,利用systemLayoutSizeFittingSize方法获取系统计算的高度后,移除添加的横向约束其中有个iOS10.2后的约束计算变化,需要我们手动对cell.contentView添加四周的约束,AutoLayout才能准确计算高度。请注意代码中对系统判断的一步

这里我们为UICollectionViewCell添加了一个Category,用于统一数据的传入方式

#import <UIKit/UIKit.h>

@interface UICollectionViewCell (FeedData)
@property (nonatomic, strong) id feedData;
@property (nonatomic, strong) id subfeedData;
@end

// --------------------------------------

#import "UICollectionViewCell+FeedData.h"
#import <objc/runtime.h>

static NSString *AssociateKeyFeedData = @"AssociateKeyFeedData";
static NSString *AssociateKeySubFeedData = @"AssociateKeySubFeedData";
@implementation UICollectionViewCell (FeedData)
@dynamic feedData;
@dynamic subfeedData;

- (void)setFeedData:(id)feedData{
    objc_setAssociatedObject(self, &AssociateKeyFeedData, feedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)feedData{
    return objc_getAssociatedObject(self, &AssociateKeyFeedData);
}

- (void)setSubfeedData:(id)subfeedData{
    objc_setAssociatedObject(self, &AssociateKeySubFeedData, subfeedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)subfeedData{
    return objc_getAssociatedObject(self, &AssociateKeySubFeedData);
}

@end

关键代码如下:

  • itemSize
- (CGSize)calculateItemSizeWithIndex:(NSInteger)index{
    NSAssert(index < self.datas.count, @"index is incorrect");
    UICollectionViewCell *tempCell = [self templateCellWithReuseIdentifier:self.reuseIdentifier withIndex:index];
    tempCell.feedData = self.datas[index];
    CGFloat cellHeight = [self systemCalculateHeightForTemplateCell:tempCell];
    return CGSizeMake(self.itemWidth, cellHeight);
}
  • 获取一个计算使用的Template Cell,保存避免重复提取
- (UICollectionViewCell *)templateCellwithIndex:(NSInteger)index{
    if (!self.templateCell) {
        if (self.className) {
            Class cellClass = NSClassFromString(self.className);
            UICollectionViewCell *templateCell = [[cellClass alloc] init];
            self.templateCell = templateCell;
        }else if (self.xibName){
            UICollectionViewCell *templateCell = [[NSBundle mainBundle] loadNibNamed:self.xibName owner:nil options:nil].lastObject;
            self.templateCell = templateCell;
        }
    }
    return self.templateCell;
}
  • AutoLayout Self-sizing
- (CGFloat)systemCalculateHeightForTemplateCell:(UICollectionViewCell *)cell{
    CGFloat calculateHeight = 0;
    
    NSLayoutConstraint *widthForceConstant = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.itemWidth];

    static BOOL isSystemVersionEqualOrGreaterThen10_2 = NO;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        isSystemVersionEqualOrGreaterThen10_2 = [UIDevice.currentDevice.systemVersion compare:@"10.2" options:NSNumericSearch] != NSOrderedAscending;
    });
    
    NSArray<NSLayoutConstraint *> *edgeConstraints;
    if (isSystemVersionEqualOrGreaterThen10_2) {
        // To avoid conflicts, make width constraint softer than required (1000)
        widthForceConstant.priority = UILayoutPriorityRequired - 1;

        // Build edge constraints
        NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        edgeConstraints = @[leftConstraint, rightConstraint, topConstraint, bottomConstraint];
        [cell addConstraints:edgeConstraints];
    }
    
    // system calculate
    [cell.contentView addConstraint:widthForceConstant];
    calculateHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    // clear constraint
    [cell.contentView removeConstraint:widthForceConstant];
    if (isSystemVersionEqualOrGreaterThen10_2) {
        [cell removeConstraints:edgeConstraints];
    }
    return calculateHeight;
}

如何使用

  • 初始化时对所有必要属性进行赋值
    SPWaterFlowLayout *flowlayout = [[SPWaterFlowLayout alloc] init];
    flowlayout.columnNumber = 2;
    flowlayout.interitemSpacing = 10;
    flowlayout.lineSpacing = 10;
    flowlayout.pageSize = 54;
    flowlayout.xibName = @"TestView";
    UICollectionView *test = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
    test.contentInset = UIEdgeInsetsMake(10, 10, 5, 10);
    [self.view addSubview:test];
    test.delegate = self;
    test.dataSource = self;
    [test registerNib:[UINib nibWithNibName:@"TestView" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    test.backgroundColor = [UIColor whiteColor];
  • Refresh及LoadMore中更新dataSource

Refresh

test.refreshDataCallBack = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.pageTag = 0;
            NSArray *datas = [SPProductModel productWithIndex:0];
            flowlayout.datas = datas;
            wtest.sp_datas = [datas mutableCopy];
            [wtest doneLoadDatas];
            [wtest reloadData];
        });
    };

LoadMore

 test.loadMoreDataCallBack = ^{
        self.pageTag ++;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSArray *datas = [SPProductModel productWithIndex:self.pageTag];
            NSArray *total = [flowlayout.datas arrayByAddingObjectsFromArray:datas];
            flowlayout.datas = total;
            wtest.sp_datas = [total mutableCopy];
            [wtest doneLoadDatas];
            [wtest reloadData];
        });
    };

效果

题外话:iPhone X让我们除了64,又记住了88和812,自己写Refresh的朋友,记得看一下contentInset 在iOS11中,如果不关autoAdjust情况下 有什么变化

waterflow.gif

Demo地址

GitHub:SPWaterFlowLayout
笔者博客地址:Tr2e's Blog


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

推荐阅读更多精彩内容