現(xiàn)在隨處可見丰辣,各種App首頁采用瀑布流展示的效果乍恐,瀑布流它是一種自定義的布局方式默蚌,比如系統(tǒng)的FlowOut流水布局樣式辆琅,直接上代碼
自定義WaterflowLayout類繼承UICollectionViewLayout
實現(xiàn)以下4個方法
@interface UICollectionWaterflowLayout : UICollectionViewLayout
/**
* 初始化
*/
- (void)prepareLayout
{
[super prepareLayout];
self.contentHeight = 0;
// 清除以前計算的所有高度
[self.columnHeights removeAllObjects];
for (NSInteger i = 0; i < self.columnCount; i++) {
[self.columnHeights addObject:@(self.edgeInsets.top)];
}
// 清除之前所有的布局屬性
[self.attrsArray removeAllObjects];
// 開始創(chuàng)建每一個cell對應(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對應(yīng)的布局屬性
UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
[self.attrsArray addObject:attrs];
}
}
/**
* 決定cell的排布
*/
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.attrsArray;
}
/**
* 返回indexPath位置cell對應(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;
}