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

前言

探究Custom Layout及应用实践

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,提高计算效率,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (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];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
- (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;
}
1
2
3
4
5
6
7
8
- (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,用于统一数据的传入方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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
    1
    2
    3
    4
    5
    6
    7
    - (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,保存避免重复提取
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    - (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
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    - (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;
    }

    如何使用

  • 初始化时对所有必要属性进行赋值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
10
11
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的朋友,记得更新下机型判断
waterflow.gif

Demo地址

SPWaterFlowLayout
笔者简书地址