iOS 淘寶首頁、電商首頁 瀑布流效果 復雜collectionView樣式

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

gif.gif

實現思路

  • 瀑布流的那個效果單獨做一個自定義的cell,里面設置瀑布流效果
  • 難度就是計算高度的問題,這個cell的高度需要去計算,每次獲取新數據的時候,都把所有數據遍歷算一遍當前數據所瀑布流布局得到的高度
  • 計算高度的時候要知道,因為我的是兩列,所以 我把數組兩個兩個變成一個組合 組成大數組,然后遍歷,計算左邊高度 和 右邊高度,相比較,哪邊矮就先把數據布局到矮的那邊,這樣就可以得到最終的左右兩邊高度,當然記得加上行間距,然后再取一下左右高度最大值得到整個瀑布流的高度。

實現代碼

//為什么要加號方法,因為我的cell高度計算是通過cell加號方法根據數據計算的,所以下面用的都是加號方法,
// 拆分數組變成2個2個一組
+ (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;
    //數組兩個兩個組成數據
    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);
    //多加了一個間距
    height -= PtOnIPhone6(7);
    height += contentHeight;
    return height;
}
//計算每個item內容高度
+(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;
}
//計算的是cell高度,根據自身的情況來
+ (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
/**
  * 每個item的高度
  */
- (CGFloat)waterFallLayout:(EWWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth;
 
@optional
/**
 * 有多少列
 */
- (NSUInteger)columnCountInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
 
/**
 * 每列之間的間距
 */
- (CGFloat)columnMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
 
/**
 * 每行之間的間距
 */
- (CGFloat)rowMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;
/**
* 每個item的內邊距
*/
- (UIEdgeInsets)edgeInsetsInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

@end
                   
@interface EWWaterFallLayout : UICollectionViewLayout

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

@end

-m文件


/** 默認的列數 */
static const CGFloat EWDefaultColumnCount = 2;
/** 每一列之間的間距 */
static const CGFloat EWDefaultColumnMargin = 7;
/** 每一行之間的間距 **/
static const CGFloat EWDefaultFRowMargin = 7;
/** 內邊距 */
static const UIEdgeInsets EWDefaultEdgeInsets = {0,0,0,0};

@interface EWWaterFallLayout()
/** 存放所有的布局屬性 */
@property (nonatomic, strong) NSMutableArray *attrsArr;
/** 存放所有列的當前高度 */
@property (nonatomic, strong) NSMutableArray *columnHeights;
/** 內容的高度 */
@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 數據處理
/**
  * 列數
 */
- (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的內邊距
 */
- (UIEdgeInsets)edgeInsets {
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterFallLayout:)]) {
        return [self.delegate edgeInsetsInWaterFallLayout:self];
    } else {
        return EWDefaultEdgeInsets;
    }
}
 
/**
 * 初始化
 */
- (void)prepareLayout {
    [super prepareLayout];
    
    self.contentHeight = 0;
    
    //清除之前計算的所有高度
    [self.columnHeights removeAllObjects];
    
    //設置每一列默認的高度
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(EWDefaultEdgeInsets.top)];
    }
    //清除之前所有的布局屬性
        [self.attrsArr removeAllObjects];
        
        //開始創建每一個cell對應的布局屬性
        NSInteger count = [self.collectionView numberOfItemsInSection:0];
        
        for (int i = 0; i < count; i++) {
            
            //創建位置
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            
            //獲取indexPath位置上cell對應的布局屬性
            UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
            
            [self.attrsArr addObject:attrs];
        }
    }
/**
 * 返回indexPath位置cell對應的布局屬性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //創建布局屬性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //collectionView的寬度
    CGFloat collectionViewW = self.collectionView.frame.size.width;
    //設置布局屬性的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));
    //記錄內容的高度 - 即最長那一列的高度
    CGFloat maxColumnHeight = [self.columnHeights[destColumn] doubleValue];
    if (self.contentHeight < maxColumnHeight) {
        self.contentHeight = maxColumnHeight;
    }
    return attrs;
}
 
/**
 * 決定cell的布局屬性
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attrsArr;
}
 
/**
 * 內容的高度
 */
- (CGSize)collectionViewContentSize {
    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
}
@end

總結

難點主要在高度的計算那塊,不要算錯了,道理都一樣,就和collectionViewlayout里面計算高度一樣。

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

上面那種寫法會存在這個問題:每次快速上拉獲取新數據會導致內存增加,CPU會閃增,再降低,視圖顯示效果不好

優化

  • 自定義UICollectionViewlayout 分區layout
具體實現,有時間寫一個demo
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,333評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,491評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,263評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,946評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,708評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,409評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,939評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,774評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,641評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,872評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,650評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容