iOS 淘寶首頁(yè)、電商首頁(yè) 瀑布流效果 復(fù)雜collectionView樣式

最近需求中需要對(duì)首頁(yè)進(jìn)行改版,插入瀑布流效果,但是我的首頁(yè)是collectionView創(chuàng)建的,里面布局太多了,不好修改,以前遇到這樣的需求,當(dāng)時(shí)直接想的不同的second設(shè)置不同的layout ,但是感覺太復(fù)雜了,對(duì)我來說有點(diǎn)難度,后面想到把上面的那部分全部設(shè)置為表頭,只留一個(gè)瀑布流的layout實(shí)現(xiàn),但是對(duì)于我們項(xiàng)目來說,這樣寫改動(dòng)太大了,我還怕改出問題,所以就有了以下方式,先看下具體效果:

gif.gif

實(shí)現(xiàn)思路

  • 瀑布流的那個(gè)效果單獨(dú)做一個(gè)自定義的cell,里面設(shè)置瀑布流效果
  • 難度就是計(jì)算高度的問題,這個(gè)cell的高度需要去計(jì)算,每次獲取新數(shù)據(jù)的時(shí)候,都把所有數(shù)據(jù)遍歷算一遍當(dāng)前數(shù)據(jù)所瀑布流布局得到的高度
  • 計(jì)算高度的時(shí)候要知道,因?yàn)槲业氖莾闪?,所?我把數(shù)組兩個(gè)兩個(gè)變成一個(gè)組合 組成大數(shù)組,然后遍歷,計(jì)算左邊高度 和 右邊高度,相比較,哪邊矮就先把數(shù)據(jù)布局到矮的那邊,這樣就可以得到最終的左右兩邊高度,當(dāng)然記得加上行間距,然后再取一下左右高度最大值得到整個(gè)瀑布流的高度。

實(shí)現(xiàn)代碼

//為什么要加號(hào)方法,因?yàn)槲业腸ell高度計(jì)算是通過cell加號(hào)方法根據(jù)數(shù)據(jù)計(jì)算的,所以下面用的都是加號(hào)方法,
// 拆分?jǐn)?shù)組變成2個(gè)2個(gè)一組
+ (NSArray *)splitArray:(NSArray *)originalArray withSubSize:(NSInteger)subSize
{
    NSInteger count = originalArray.count % subSize == 0 ? (originalArray.count / subSize) : (originalArray.count / subSize + 1);
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < count; i ++) {
        NSInteger j = i * subSize;
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        while (j < subSize*(i + 1) && j < originalArray.count) {
            [tempArray addObject:[originalArray objectAtIndex:j]];
            j += 1;
        }
        [newArray addObject:[tempArray copy]];
    }
    return [newArray copy];
}

+(CGFloat)caculateEndHeight:(OSFlowVideoModel *)model
{

    CGFloat height = 0.0;
    //左邊的高度
    CGFloat leftHeight = 0.0;
    //右邊的高度
    CGFloat rightHeight = 0.0;
    //最終高度
    CGFloat contentHeight = 0.0;
    //數(shù)組兩個(gè)兩個(gè)組成數(shù)據(jù)
    NSArray *array = [self splitArray:model.list withSubSize:2];
    for (int i = 0; i<array.count; i++) {
        NSArray *arr = array[i];
        for (int j = 0; j<2; j++) {
            OSFlowVideoItemModel *a = arr[j];
            if (leftHeight > rightHeight) {
                rightHeight = rightHeight + [self caculateContentHeight:a] + PtOnIPhone6(7);
            }else{
                leftHeight = leftHeight + [self caculateContentHeight:a] + PtOnIPhone6(7);
            }
        }
    }
    contentHeight =  MAX(leftHeight, rightHeight);
    //多加了一個(gè)間距
    height -= PtOnIPhone6(7);
    height += contentHeight;
    return height;
}
//計(jì)算每個(gè)item內(nèi)容高度
+(CGFloat)caculateContentHeight:(OSFlowVideoItemModel *)item
{
    CGFloat itemWidth = (OSScreenWidth - PtOnIPhone6(32) - PtOnIPhone6(7))/2;
    CGFloat height = 0.0;
    CGFloat titleH = [OSUtiltity getHeightWithText:item.title width:itemWidth - PtOnIPhone6(12) fontSize:RegularSysFont(14) withLimitHeight:PtOnIPhone6(40)];
    CGFloat imageHeight = 0.0;
    if (item.width.floatValue > item.height.floatValue) {
        imageHeight = itemWidth*3/4;
    }else if (item.width.floatValue < item.height.floatValue){
        imageHeight = itemWidth*4/3;
    }else{
        imageHeight = itemWidth;
    }
    height = titleH + imageHeight + PtOnIPhone6(16) + PtOnIPhone6(11) + PtOnIPhone6(20) + PtOnIPhone6(16);
    return height;
}
//計(jì)算的是cell高度,根據(jù)自身的情況來
+ (CGFloat)heightWithItems:(NSArray<OSStyleBaseItem *> *)items indexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    OSFlowVideoModel *model = (OSFlowVideoModel *)items[indexPath.row];
    return  [self caculateEndHeight:model];
}

瀑布流的collectionViewlayout

  • h文件
@class EWWaterFallLayout;
 
@protocol EWWaterFallLayoutDataSource<NSObject>
 
@required
/**
  * 每個(gè)item的高度
  */
- (CGFloat)waterFallLayout:(EWWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth;
 
@optional
/**
 * 有多少列
 */
- (NSUInteger)columnCountInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
 
/**
 * 每列之間的間距
 */
- (CGFloat)columnMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
 
/**
 * 每行之間的間距
 */
- (CGFloat)rowMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
/**
* 每個(gè)item的內(nèi)邊距
*/
- (UIEdgeInsets)edgeInsetsInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

@end
                   
@interface EWWaterFallLayout : UICollectionViewLayout

/**
* 代理
*/
@property (nonatomic, weak) id<EWWaterFallLayoutDataSource> delegate;

@end

-m文件


/** 默認(rèn)的列數(shù) */
static const CGFloat EWDefaultColumnCount = 2;
/** 每一列之間的間距 */
static const CGFloat EWDefaultColumnMargin = 7;
/** 每一行之間的間距 **/
static const CGFloat EWDefaultFRowMargin = 7;
/** 內(nèi)邊距 */
static const UIEdgeInsets EWDefaultEdgeInsets = {0,0,0,0};

@interface EWWaterFallLayout()
/** 存放所有的布局屬性 */
@property (nonatomic, strong) NSMutableArray *attrsArr;
/** 存放所有列的當(dāng)前高度 */
@property (nonatomic, strong) NSMutableArray *columnHeights;
/** 內(nèi)容的高度 */
@property (nonatomic, assign) CGFloat contentHeight;

- (NSUInteger)columnCount;
- (CGFloat)columnMargin;
- (CGFloat)rowMargin;
- (UIEdgeInsets)edgeInsets;

@end
@implementation EWWaterFallLayout
- (NSMutableArray *)attrsArr {
    if (!_attrsArr) {
        _attrsArr = [NSMutableArray array];
    }
    return _attrsArr;
}
 
- (NSMutableArray *)columnHeights {
    if (!_columnHeights) {
        _columnHeights = [NSMutableArray array];
    }
    return _columnHeights;
}
 
#pragma mark 數(shù)據(jù)處理
/**
  * 列數(shù)
 */
- (NSUInteger)columnCount {
    if ([self.delegate respondsToSelector:@selector(columnCountInWaterFallLayout:)]) {
        return [self.delegate columnCountInWaterFallLayout:self];
    } else {
        return EWDefaultColumnCount;
    }
}

/**
 * 列間距
 */
- (CGFloat)columnMargin {
    if ([self.delegate respondsToSelector:@selector(columnMarginInWaterFallLayout:)]) {
        return [self.delegate columnMarginInWaterFallLayout:self];
    } else {
        return EWDefaultColumnMargin;
    }
}
 
/**
 * 行間距
 */
- (CGFloat)rowMargin {
    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterFallLayout:)]) {
        return [self.delegate rowMarginInWaterFallLayout:self];
    } else {
        return EWDefaultFRowMargin;
    }
}

/**
 * item的內(nèi)邊距
 */
- (UIEdgeInsets)edgeInsets {
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterFallLayout:)]) {
        return [self.delegate edgeInsetsInWaterFallLayout:self];
    } else {
        return EWDefaultEdgeInsets;
    }
}
 
/**
 * 初始化
 */
- (void)prepareLayout {
    [super prepareLayout];
    
    self.contentHeight = 0;
    
    //清除之前計(jì)算的所有高度
    [self.columnHeights removeAllObjects];
    
    //設(shè)置每一列默認(rèn)的高度
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(EWDefaultEdgeInsets.top)];
    }
    //清除之前所有的布局屬性
        [self.attrsArr removeAllObjects];
        
        //開始創(chuàng)建每一個(gè)cell對(duì)應(yīng)的布局屬性
        NSInteger count = [self.collectionView numberOfItemsInSection:0];
        
        for (int 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.attrsArr addObject:attrs];
        }
    }
/**
 * 返回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 cellW = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;
    CGFloat cellH = [self.delegate waterFallLayout:self heightForItemAtIndexPath:indexPath.item itemWidth:cellW];
    //找出最短的那一列
    NSInteger destColumn = 0;
    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
    for (int i = 0; i < self.columnCount; i++) {
        //取得第i列的高度
        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
        if (minColumnHeight > columnHeight) {
            minColumnHeight = columnHeight;
            destColumn = i;
        }
    }
    CGFloat cellX = self.edgeInsets.left + destColumn * (cellW + self.columnMargin);
    CGFloat cellY = minColumnHeight;
    if (cellY != self.edgeInsets.top) {
        cellY += self.rowMargin;
    }
    attrs.frame = CGRectMake(cellX, cellY, cellW, cellH);
    //更新最短那一列的高度
    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
    //記錄內(nèi)容的高度 - 即最長(zhǎng)那一列的高度
    CGFloat maxColumnHeight = [self.columnHeights[destColumn] doubleValue];
    if (self.contentHeight < maxColumnHeight) {
        self.contentHeight = maxColumnHeight;
    }
    return attrs;
}
 
/**
 * 決定cell的布局屬性
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attrsArr;
}
 
/**
 * 內(nèi)容的高度
 */
- (CGSize)collectionViewContentSize {
    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
}
@end

總結(jié)

難點(diǎn)主要在高度的計(jì)算那塊,不要算錯(cuò)了,道理都一樣,就和collectionViewlayout里面計(jì)算高度一樣。

========2022.1.15更新==========

上面那種寫法會(huì)存在這個(gè)問題:每次快速上拉獲取新數(shù)據(jù)會(huì)導(dǎo)致內(nèi)存增加,CPU會(huì)閃增,再降低,視圖顯示效果不好

優(yōu)化

  • 自定義UICollectionViewlayout 分區(qū)layout
具體實(shí)現(xiàn),有時(shí)間寫一個(gè)demo
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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