瀑布流效果

現(xiàn)在隨處可見(jiàn),各種App首頁(yè)采用瀑布流展示的效果,瀑布流它是一種自定義的布局方式,比如系統(tǒng)的FlowOut流水布局樣式,直接上代碼

自定義WaterflowLayout類(lèi)繼承UICollectionViewLayout

實(shí)現(xiàn)以下4個(gè)方法

@interface UICollectionWaterflowLayout : UICollectionViewLayout

/**

* 初始化

*/

- (void)prepareLayout

{

[super prepareLayout];

self.contentHeight = 0;

// 清除以前計(jì)算的所有高度

[self.columnHeights removeAllObjects];

for (NSInteger i = 0; i < self.columnCount; i++) {

[self.columnHeights addObject:@(self.edgeInsets.top)];

}

// 清除之前所有的布局屬性

[self.attrsArray removeAllObjects];

// 開(kāi)始創(chuàng)建每一個(gè)cell對(duì)應(yīng)的布局屬性

NSInteger count = [self.collectionView numberOfItemsInSection:0];

for (NSInteger i = 0; i < count; i++) {

// 創(chuàng)建位置

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];

// 獲取indexPath位置cell對(duì)應(yīng)的布局屬性

UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];

[self.attrsArray addObject:attrs];

}

}

/**

* 決定cell的排布

*/

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

{

return self.attrsArray;

}


/**

* 返回indexPath位置cell對(duì)應(yīng)的布局屬性

*/

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{

// 創(chuàng)建布局屬性

UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

// collectionView的寬度

CGFloat collectionViewW = self.collectionView.frame.size.width;

// 設(shè)置布局屬性的frame

CGFloat w = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;

CGFloat h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath.item itemWidth:w];

// 找出高度最短的那一列

NSInteger destColumn = 0;

CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];

for (NSInteger i = 1; i < self.columnCount; i++) {

// 取得第i列的高度

CGFloat columnHeight = [self.columnHeights[i] doubleValue];

if (minColumnHeight > columnHeight) {

minColumnHeight = columnHeight;

destColumn = i;

}

}

CGFloat x = self.edgeInsets.left + destColumn * (w + self.columnMargin);

CGFloat y = minColumnHeight;

if (y != self.edgeInsets.top) {

y += self.rowMargin;

}

attrs.frame = CGRectMake(x, y, w, h);

// 更新最短那列的高度

self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));

// 記錄內(nèi)容的高度

CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];

if (self.contentHeight < columnHeight) {

self.contentHeight = columnHeight;

}

return attrs;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容