官方描述
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 -(void)prepareLayout
将被调用,默认下该方法什么没作,可是在本身的子类实现中,通常在该方法中设定一些必要的layout的
结构和初始须要的参数等 -(CGSize) collectionViewContentSize
将被调用,以肯定collection
应该占据的尺寸。注意这里的尺寸不是指可视部分的尺寸,而应该是全部内容所占的尺寸。collectionView
的本质是一个scrollView
,所以须要这个尺寸来配置滚动行为 -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
网上前辈们已经写烂了,这里只简述:服务器
-(void)prepareLayout
中:就是经过一个记录列高度的数组(或字典),在建立LayoutAttributes
的frame时肯定当前最短列,根据外部传入的相关的spacing
及collectionView
的inset
属性,肯定宽度、frame等信息,存入Attributes的数组。-(CGSize) collectionViewContentSize
中:经过列高度数组很容易肯定当前范围,contentSize不等于collectionview的bounds.size,计算时留意一下-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
:返回第一步中计算得到的Attributes数组便可以上能够帮助咱们实现一个瀑布流的效果,可是离实际应用还有一段差距。网络
分析:
实际应用中,咱们的网络请求是会有一个pageSize的,并且列表的赋值一般是直接进行数据源的赋值而后reloadData
。因此数据源个数等于pageSize时,咱们认为是刷新,大于时,则为分页加载。
根据这套逻辑,这里将pageSize及dataSource做为属性引入到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
注意:布局
自动计算的思路,相似UITableView-FDTemplateLayoutCell,经过xibName或className初始化一个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
关键代码以下:
- (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); }
- (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; }
- (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];
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的朋友,记得更新下机型判断