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 askedgit

官方文档github

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

- (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,经过这个属性能够帮助咱们减小没必要要的重复计算ide

关于自动计算

注意布局

  • Self-size要求咱们的约束自上而下设置,确保可以经过Constraint计算得到准确的高度。具体再也不赘述
  • 本Demo仅适用图片比例肯定的瀑布流,若是需求是图片size自适应,须要服务器返回可以计算的必要参数

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

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

#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的朋友,记得更新下机型判断
waterflow.gif

Demo地址

SPWaterFlowLayout
笔者简书地址

相关文章
相关标签/搜索