上篇博客的實(shí)例是自帶的UICollectionViewDelegateFlowLayout布局基礎(chǔ)上來做的Demo, 詳情請(qǐng)看《iOS開發(fā)之UICollectionViewController系列(二) –詳解CollectionView各種回調(diào)》。UICollectionView之所以強(qiáng)大翰苫,是因?yàn)槠渚哂凶远x功能,這一自定義就不得了啦,自由度非常大砰奕,定制的高甚纲,所以功能也是灰常強(qiáng)大的纱烘。本篇博客就不使用自帶的流式布局了,我們要自定義一個(gè)瀑布流棕所。自定義的瀑布流可以配置其參數(shù): 每個(gè)Cell的邊距,共有多少列悯辙,Cell的最大以及最小高度是多少等琳省。
一.先入為主
先來看一下不同配置參數(shù)下運(yùn)行后的效果吧,每張截圖的列數(shù)和Cell之間的邊距都有所不同躲撰,瀑布流的列數(shù)依次為2针贬,3,8拢蛋。有密集恐懼證的童鞋就不要看這些運(yùn)行效果圖了桦他,真的會(huì)看暈的。下面這些運(yùn)行效果就是修改不同的配置參數(shù)來進(jìn)行布局的谆棱∷仓看圖吧,關(guān)于瀑布流的效果就不啰嗦了础锐。以下的效果就是使用自定義布局做的嗓节,接下來將會(huì)介紹一下其實(shí)現(xiàn)原理。
二. UICollectionViewLayout
在介紹上述效果實(shí)現(xiàn)原理之前皆警,需要介紹一下UICollectionViewLayout拦宣。UICollectionView的自定義功能就是自己去實(shí)現(xiàn)UICollectionViewLayout的子類,然后重寫相應(yīng)的方法來實(shí)現(xiàn)Cell的布局信姓,先介紹一下需要重寫的方法鸵隧,然后再此方法上進(jìn)行應(yīng)用實(shí)現(xiàn)上述瀑布流。好意推,廢話少說豆瘫,干活走起。
1.布局預(yù)加載函數(shù)
當(dāng)布局首次被加載時(shí)會(huì)調(diào)用prepareLayout函數(shù)菊值,見名知意外驱,就是預(yù)先加載布局育灸,在該方法中可以去初始化布局相關(guān)的數(shù)據(jù)。該方法類似于視圖控制器的ViewDidLoad方法昵宇,稍后回用到該方法磅崭。
Objective-C
// The collection view calls -prepareLayout once at its first layout as the first message to the layout instance.
// The collection view calls -prepareLayout again after layout is invalidated and before requerying the layout information.
// Subclasses should always call super if they override. - (void)prepareLayout;
// The collection view calls -prepareLayout once at its first layout as the first message to the layout instance.
// The collection view calls -prepareLayout again after layout is invalidated and before requerying the layout information.
// Subclasses should always call super if they override.
- (void)prepareLayout;
2.內(nèi)容滾動(dòng)范圍
下方是定義ContentSize的方法。該方法會(huì)返回CollectionView的大小瓦哎,這個(gè)方法也是自定義布局中必須實(shí)現(xiàn)的方法砸喻。說白了,就是設(shè)置ScrollView的ContentSize蒋譬,即滾動(dòng)區(qū)域割岛。
Objective-C
// Subclasses must override this method and use it to return the width and height of the collection view’s content. These values represent the width and height of all the content, not just the content that is currently visible. The collection view uses this information to configure its own content size to facilitate scrolling.
- (CGSize)collectionViewContentSize;
- 下方四個(gè)方法是確定布局屬性的,下方第一個(gè)方法返回一個(gè)數(shù)組犯助,該數(shù)組中存放的是為每個(gè)Cell綁定的UICollectionViewLayoutAttributes屬性癣漆,便于在下面第二個(gè)方法中去定制每個(gè)Cell的屬性。第三個(gè)方法就是根據(jù)indexPath來獲取Cell所綁定的layoutAtrributes, 然后去更改UICollectionViewLayoutAttributes對(duì)象的一些屬性并返回也切,第四個(gè)是為Header View或者FooterView來定制其對(duì)應(yīng)的UICollectionViewLayoutAttributes扑媚,然后返回。
Objective-C
// UICollectionView calls these four methods to determine the layout information.
// Implement -layoutAttributesForElementsInRect: to return layout attributes for for supplementary or decoration views, or to perform layout in an as-needed-on-screen fashion.
// Additionally, all layout subclasses should implement -layoutAttributesForItemAtIndexPath: to return layout attributes instances on demand for specific index paths.
// If the layout supports any supplementary or decoration view types, it should also implement the respective atIndexPath: methods for those types.
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath;
- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)elementKind atIndexPath:(NSIndexPath *)indexPath;
4.UICollectionViewLayoutAttributes
下方是UICollectionViewLayoutAttributes常用的屬性雷恃,你可以在上面第二個(gè)方法中去為下方這些屬性賦值疆股,為Cell定制屬于自己的Attributes。由下方的屬性就對(duì)自定義布局的的強(qiáng)大倒槐,在本篇博客中只用到了下方的一個(gè)屬性旬痹,那就是frame。
Objective-C
@property (nonatomic) CGRect frame;
@property (nonatomic) CGPoint center;
@property (nonatomic) CGSize size;
@property (nonatomic) CATransform3D transform3D;
@property (nonatomic) CGRect bounds NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGAffineTransform transform NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGFloat alpha;
@property (nonatomic) NSInteger zIndex; // default is 0
@property (nonatomic, getter=isHidden) BOOL hidden; // As an optimization, UICollectionView might not create a view for items whose hidden attribute is YES
三. UICollectionViewLayout的應(yīng)用
經(jīng)過上面的簡(jiǎn)單介紹讨越,想必對(duì)UICollectionViewLayout有一定的了解吧两残,UICollectionViewLayout中還有好多方法,以后用到的時(shí)候在給大家介紹把跨。接下來要使用自定義布局來實(shí)現(xiàn)瀑布流人弓。我們需要在UICollectionViewLayout的子類中實(shí)現(xiàn)相應(yīng)的布局方法,因?yàn)閁ICollectionViewLayout是虛基類着逐,是不能直接被實(shí)例化的崔赌,所以我們需要新建一個(gè)布局類,這個(gè)布局類繼承自UICollectionViewLayout耸别。然后去實(shí)現(xiàn)上述方法健芭,給每個(gè)Cell定制不同的UICollectionViewLayoutAttributes。好了還是拿代碼說話吧秀姐。
1.重寫prepareLayout方法去初始化一些數(shù)據(jù)慈迈,該方法在CollectionView重新加載時(shí)只會(huì)調(diào)用一次,所以把一些參數(shù)的配置省有,計(jì)算每個(gè)Cell的寬度痒留,每個(gè)Cell的高度等代碼放在預(yù)處理函數(shù)中谴麦。在該函數(shù)中具體調(diào)用的函數(shù)如下所示:
Objective-C
#pragma mark -- 虛基類中重寫的方法
/**
* 該方法是預(yù)加載layout, 只會(huì)被執(zhí)行一次
*/
- (void)prepareLayout{
[super prepareLayout];
[self initData];
[self initCellWidth];
[self initCellHeight];
}
2.返回內(nèi)容的范圍,即為CollectionView設(shè)定ContentSize狭瞎。ContentSize的Width就是屏幕的寬度细移,而ContentSize的高度是一列中最后一個(gè)Cell的Y坐標(biāo)加上其自身高度的最大值搏予。在此函數(shù)中會(huì)調(diào)用求CellY數(shù)組中的最大值熊锭。具體實(shí)現(xiàn)代碼如下:
Objective-C
/**
* 該方法返回CollectionView的ContentSize的大小
*/
- (CGSize)collectionViewContentSize{
CGFloat height = [self maxCellYArrayWithArray:_cellYArray];
return CGSizeMake(SCREEN_WIDTH, height);
}
3.下面的方法是為每個(gè)Cell去綁定一個(gè)UICollectionViewLayoutAttributes對(duì)象,并且以數(shù)組的形式返回雪侥,在我們的自定義瀑布流中碗殷,我們只自定義了Cell的frame,就可以實(shí)現(xiàn)我們的瀑布流,UICollectionViewLayoutAttributes的其他屬性我們沒有用到速缨,由此可以看出自定義Cell布局功能的強(qiáng)大锌妻。
Objective-C
/**
* 該方法為每個(gè)Cell綁定一個(gè)Layout屬性~
*/
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
[self initCellYArray];
NSMutableArray *array = [NSMutableArray array];
//add cells
for (int i=0; i )
{
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
[array addObject:attributes];
}
return array;
}
- 通過下述方法設(shè)定每個(gè)Cell的UICollectionViewLayoutAttributes對(duì)象的參數(shù),為了實(shí)現(xiàn)瀑布流所以我們只需要設(shè)置每個(gè)Cell的frame即可旬牲。每個(gè)cell的frame的確定是以列來定的仿粹,有所在列的上個(gè)Cell的Y坐標(biāo)來確定下個(gè)cell的位置。瀑布流實(shí)現(xiàn)關(guān)鍵點(diǎn)如下:
(1)Cell寬度計(jì)算:如果瀑布流的列數(shù)和Cell的Padding確定了原茅,那么每個(gè)Cell的寬度再通過屏幕的寬度就可以計(jì)算出來了吭历。
(2)Cell高度計(jì)算:通過隨機(jī)數(shù)生成的高度
(3)Cell的X軸坐標(biāo)計(jì)算:通過列數(shù),和Padding擂橘,以及每個(gè)Cell的寬度很容易就可以計(jì)算出每個(gè)Cell的X坐標(biāo)晌区。
(4)Cell的Y軸坐標(biāo)計(jì)算:通過Cell所在列的上一個(gè)Cell的Y軸坐標(biāo),Padding, 和 上一個(gè)Cell的高度就可以計(jì)算下一個(gè)Cell的Y坐標(biāo)通贞,并記錄在Y坐標(biāo)的數(shù)組中了朗若。
Objective-C
/**
* 該方法為每個(gè)Cell綁定一個(gè)Layout屬性~
*/
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGRect frame = CGRectZero;
CGFloat cellHeight = [_cellHeightArray[indexPath.row] floatValue];
NSInteger minYIndex = [self minCellYArrayWithArray:_cellYArray];
CGFloat tempX = [_cellXArray[minYIndex] floatValue];
CGFloat tempY = [_cellYArray[minYIndex] floatValue];
frame = CGRectMake(tempX, tempY, _cellWidth, cellHeight);
//更新相應(yīng)的Y坐標(biāo)
_cellYArray[minYIndex] = @(tempY + cellHeight + _padding);
//計(jì)算每個(gè)Cell的位置
attributes.frame = frame;
return attributes;
}
- initData方法主要是對(duì)數(shù)據(jù)進(jìn)行初始化,在本篇博客中為了先實(shí)現(xiàn)效果昌罩,我們暫且把數(shù)據(jù)給寫死哭懈。下篇博客會(huì)在本篇博客中的基礎(chǔ)上進(jìn)行優(yōu)化和改進(jìn),這些配置參數(shù)都會(huì)在Delegate中提供茎用,便于靈活的去定制屬于你自己的瀑布流遣总。本篇博客中Demo的配置項(xiàng)先寫死就OK了,還是那句話绘搞,下篇博客中會(huì)給出一些相應(yīng)的代理彤避,來定制我們的瀑布流。
Objective-C
/**
* 初始化相關(guān)數(shù)據(jù)
*/
- (void) initData{
_numberOfSections = [self.collectionView numberOfSections];
_numberOfCellsInSections = [self.collectionView numberOfItemsInSection:0];
//通過回調(diào)獲取列數(shù)
_columnCount = 5;
_padding = 5;
_cellMinHeight = 50;
_cellMaxHeight = 150;
}
6.下方的方法是根據(jù)Cell的列數(shù)來求出Cell的寬度夯辖。因?yàn)镃ell的寬度都是一樣的琉预,每個(gè)Cell的間隔也是一定的。例如有5列Cell, 那么Cell中間的間隔就有4(5-1)個(gè)蒿褂,那么每個(gè)Cell的寬度就是屏幕的寬度減去所有間隔的寬度圆米,再除以列數(shù)就是Cell的寬度卒暂。如果沒聽我啰嗦明白的話,直接看代碼吧娄帖,并不復(fù)雜也祠。每個(gè)Cell的寬度和間隔確定了,那么每個(gè)Cell的X軸坐標(biāo)也就確定了近速。代碼如下:
Objective-C
/**
* 根據(jù)Cell的列數(shù)求出Cell的寬度
*/
- (void) initCellWidth{
//計(jì)算每個(gè)Cell的寬度
_cellWidth = (SCREEN_WIDTH - (_columnCount -1) * _padding) / _columnCount;
//為每個(gè)Cell計(jì)算X坐標(biāo)
_cellXArray = [[NSMutableArray alloc] initWithCapacity:_columnCount];
for (int i = 0; i ) {
CGFloat tempX = i * (_cellWidth + _padding);
[_cellXArray addObject:@(tempX)];
}
}
- 根據(jù)Cell的最小高度和最大高度來利用隨機(jī)數(shù)計(jì)算每個(gè)Cell的高度诈嘿,把每個(gè)Cell的高度記錄在數(shù)組中,便于Cell加載時(shí)使用削葱。具體代碼如下:
Objective-C
/**
* 隨機(jī)生成Cell的高度
*/
- (void) initCellHeight{
//隨機(jī)生成Cell的高度
_cellHeightArray = [[NSMutableArray alloc] initWithCapacity:_numberOfCellsInSections];
for (int i = 0; i ) {
CGFloat cellHeight = arc4random() % (_cellMaxHeight - _cellMinHeight) + _cellMinHeight;
[_cellHeightArray addObject:@(cellHeight)];
}
}
8.初始化Cell的Y軸坐標(biāo)數(shù)組奖亚,因?yàn)槭瞧俨剂鳎俨剂鞯奶攸c(diǎn)是每列中Cell的X軸坐標(biāo)是相同的析砸,我們只需要根據(jù)本列上一個(gè)Cell的Y軸坐標(biāo)來確定本列中將要插入Cell的Y軸坐標(biāo)昔字,所有我們需要維護(hù)一個(gè)每列當(dāng)前Cell的Y軸坐標(biāo)數(shù)組。其初始化方法如下:
Objective-C
/**
* 初始化每列Cell的Y軸坐標(biāo)
*/
- (void) initCellYArray{
_cellYArray = [[NSMutableArray alloc] initWithCapacity:_columnCount];
for (int i = 0; i ) {
[_cellYArray addObject:@(0)];
}
}
9.下面的方法是求Cell的Y軸坐標(biāo)數(shù)組的最大值首繁,因?yàn)樵贑ell都加載完畢后作郭,Cell數(shù)組中最大值就是CollectionView的ContentSize的Height的值。
Objective-C
/**
* 求CellY數(shù)組中的最大值并返回
*/
- (CGFloat) maxCellYArrayWithArray: (NSMutableArray *) array{
if (array.count == 0) {
return 0.0f;
}
CGFloat max = [array[0] floatValue];
for (NSNumber *number in array) {
CGFloat temp = [number floatValue];
if (max temp) {
max = temp;
}
}
return max;
}
10.下方代碼是求CellY數(shù)組中的第一個(gè)最小值的索引弦疮,因?yàn)榍蟪鲞@個(gè)CellY數(shù)組中的第一個(gè)Cell最新值得索引就是Cell應(yīng)該插入的列夹攒。
Objective-C
/**
* 求CellY數(shù)組中的最小值的索引
*/
- (CGFloat) minCellYArrayWithArray: (NSMutableArray *) array{
if (array.count == 0) {
return 0.0f;
}
NSInteger minIndex = 0;
CGFloat min = [array[0] floatValue];
for (int i = 0; i ) {
CGFloat temp = [array[i] floatValue];
if (min > temp) {
min = temp;
minIndex = i;
}
}
return minIndex;
}
自定義集合視圖控制器布局第一階段就先到這,下篇博客會(huì)在此基礎(chǔ)上進(jìn)一步開發(fā)挂捅。把上述寫死的配置參數(shù)芹助,通過Delegate提供,使其在UICollectionView可進(jìn)行配置闲先,其配置方式類似于UICollectionViewDelegateFlowLayout的代理方法状土。
如果您是iOS開發(fā)者,或者對(duì)本篇文章感興趣伺糠,請(qǐng)關(guān)注本人蒙谓,后續(xù)會(huì)更新更多相關(guān)文章!敬請(qǐng)期待训桶!
參考文章:
iOS開發(fā)之窺探UICollectionViewController(三) --使用UICollectionView自定義瀑布流