CollectionView-自定義Item排布

之前寫git商城的時候看到類似需求自定義的item排布,這兩天有人又問到我具體怎么樣自定義layout來實現(xiàn),所以寫了demo來分享下實現(xiàn)的過程。

類似APP實現(xiàn)截圖
某商場截圖
demo實現(xiàn)效果圖
demo實現(xiàn)效果圖

下面具體分析實現(xiàn)步驟

1.首先初始化懶加載一個CollectionView,注冊Cell,Header,F(xiàn)ooter~

#pragma mark - LazyLoad
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        DCItemSortLayout *dcLayout = [DCItemSortLayout new];
        dcLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:dcLayout];
        _collectionView.frame = self.view.bounds;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

        _collectionView.alwaysBounceVertical = YES;
        [self.view addSubview:_collectionView];
        
        [self.collectionView registerClass:[DCCollectionItemCell class] forCellWithReuseIdentifier:DCCollectionItemCellID]; //注冊cell
        
        [self.collectionView registerClass:[DCHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:DCHeaderReusableViewID]; //注冊頭部
        [self.collectionView registerClass:[DCFooterReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:DCFooterReusableViewID]; //注冊尾部
    }
    return _collectionView;
}

2.自定義DCItemSortLayout 在.h寫兩個代理方法,返回每組section頭部和尾部的高度

@protocol DCItemSortLayoutDelegate <NSObject>

@optional;

/* 頭部高度 */
-(CGFloat)dc_HeightOfSectionHeaderForIndexPath:(NSIndexPath *)indexPath;
/* 尾部高度 */
-(CGFloat)dc_HeightOfSectionFooterForIndexPath:(NSIndexPath *)indexPath;

@end

@interface DCItemSortLayout : UICollectionViewFlowLayout


@property (nonatomic, assign) id<DCItemSortLayoutDelegate>delegate;

3.在DCItemSortLayout .m文件中調(diào)用prepareLayout方法,聲明一個高度和可變字典

@property (nonatomic, assign) CGFloat overallHeight;     //整體高
@property (nonatomic, strong) NSMutableArray *attrsArr;  //布局?jǐn)?shù)組
/**
 1.一個Cell對應(yīng)一個UICollectionViewLayoutAttributes對象
 2.UICollectionViewLayoutAttributes對象決定了cell的擺設(shè)位置(frame)
 */
#pragma mark - 初始化屬性(section/item)
- (void)setUpAttributes
{
    NSMutableArray *attributesArray = [NSMutableArray array];
    NSInteger sectionCount = [self.collectionView numberOfSections];
    for (int i = 0; i < sectionCount; i++) { //遍歷
        //sectionHeader
        NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:i];
        UICollectionViewLayoutAttributes *attrheader = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
        [attributesArray addObject:attrheader];
    
        //sectionItem
        NSInteger itemCount = [self.collectionView numberOfItemsInSection:i];
        for (int j = 0; j < itemCount; j++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
            [attributesArray addObject:attrs];
        }
        //sectionfooter
        UICollectionViewLayoutAttributes *attrFooter = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:indexPath];
        [attributesArray addObject:attrFooter];
    }
    
    self.attrsArr = [NSMutableArray arrayWithArray:attributesArray];
}
#pragma mark - 對應(yīng)indexPath的位置的追加視圖的布局屬性
-(UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes *layoutAttrbutes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
    CGFloat height = 0;
    
    if (elementKind == UICollectionElementKindSectionHeader) { //頭部
        if (_delegate != nil && [_delegate respondsToSelector:@selector(dc_HeightOfSectionHeaderForIndexPath:)]) {
            height = [_delegate dc_HeightOfSectionHeaderForIndexPath:indexPath];
        }
    } else { //尾部
        if (_delegate != nil && [_delegate respondsToSelector:@selector(dc_HeightOfSectionFooterForIndexPath:)]) {
            height = [_delegate dc_HeightOfSectionFooterForIndexPath:indexPath];
        }
    }
    layoutAttrbutes.frame = CGRectMake(0, self.overallHeight, ScreenW, height);
    
    self.overallHeight += height;
    
    return layoutAttrbutes;
}
#pragma mark - 返回rect中的所有的元素的布局屬性
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    
    return self.attrsArr;
}
在我寫的demo中我自定義了兩組section
第一組
很明顯的可以看出 上面這一組中有4個item,代碼實現(xiàn)如下
#pragma mark - 自定義第一組section
- (void)layoutAttributesForCustomOneLayout:(UICollectionViewLayoutAttributes *)layoutAttributes indexPath: (NSIndexPath *) indexPath {
    
    CGFloat itemY = self.overallHeight;
    
    if (indexPath.item == 0) {
        CGFloat itemH = 80;
        layoutAttributes.frame = CGRectMake(0, itemY, ScreenW, itemH);
        
        self.overallHeight += itemH;
        
    } else {

        NSInteger row = (indexPath.item -1) % 3;
        CGFloat itemH = 100;
        CGFloat itemW = ScreenW / 3;
        
        layoutAttributes.frame = CGRectMake(row * itemW, itemY, itemW, itemH);
        
        if (indexPath.item == 3 || indexPath.item == [self.collectionView numberOfItemsInSection:indexPath.section] - 1) {
            
            self.overallHeight += itemH;
        }
    }
}
第二組
這一組中有3個item,代碼實現(xiàn)如下
#pragma mark - 自定義第二組section
- (void)layoutAttributesForCustomTwolayout:(UICollectionViewLayoutAttributes *)layoutAttributes indexPath: (NSIndexPath *) indexPath {
    
    CGFloat itemY = self.overallHeight;
    CGFloat itemW = ScreenW / 2;
    CGFloat itemH = 160;
    
    switch (indexPath.item) {
        case 0:
            layoutAttributes.frame = CGRectMake(0, itemY, itemW, itemH);
            break;
        case 1:
            layoutAttributes.frame = CGRectMake(itemW, itemY, itemW, itemH/2);
            break;
        case 2:
            layoutAttributes.frame = CGRectMake(itemW, (itemH/2) + itemY, itemW, itemH / 2.0);
            break;
        default:
            break;
    }
    
    
    if (indexPath.item == [self.collectionView numberOfItemsInSection:indexPath.section] - 1) {
        self.overallHeight += itemH;
    }
}

這樣我們在自定義的UICollectionViewFlowLayout中已經(jīng)完成了對兩組Items的布局,接下來我們來到控制器界面~

數(shù)據(jù)源UICollectionViewDataSource

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return (section == 0) ? 4 : 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        DCCollectionItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:DCCollectionItemCellID forIndexPath:indexPath];
        cell.backgroundColor = [self RandomColor];
        return cell;
    }else{
        
        DCCollectionItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:DCCollectionItemCellID forIndexPath:indexPath];
        cell.backgroundColor = [self RandomColor];
        return cell;
    }
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        DCHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:DCHeaderReusableViewID forIndexPath:indexPath];
        headerView.headLabel.text = [NSString stringWithFormat:@"第%zd組頭部",indexPath.section];
        return headerView;
        
    } else if (kind == UICollectionElementKindSectionFooter) {
        
        DCFooterReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:DCFooterReusableViewID forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor lightGrayColor];
        return footerView;
    }
    
    return [UICollectionReusableView new];
}

代理注意包括我們自定義的代理 DCItemSortLayoutDelegate,UICollectionViewDelegate

#pragma mark - UICollectionViewDelegate
#pragma mark - item點擊
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"點擊了第%zd組,第%zd個item",indexPath.section ,indexPath.row);
}

#pragma mark - DCItemSortLayoutDelegate
#pragma mark - 底部高度
-(CGFloat)dc_HeightOfSectionFooterForIndexPath:(NSIndexPath *)indexPath {
    return 20;
}
#pragma mark - 頭部高度
-(CGFloat)dc_HeightOfSectionHeaderForIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
  • 這樣自定義layout就完成了,之前也參考過幾個git上幾個哥們的布局對于自定義layout 的理解,很有收獲非常感謝~
  • 如上實現(xiàn)源碼基本已全部展示,如果有需要我寫的demo,可以給我留言私法~
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,808評論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,836評論 18 139
  • "偉大的民族,以三種手稿撰寫自己的傳記:行為之書,言詞之書與藝術(shù)之書。我們只有閱讀了其中的兩部書,才能理解它們中的...
    易悅精英閱讀 610評論 0 0
  • 這場叫人生的旅途,只有一條直行的路線,沒有任何拐彎可重新回到一點重新經(jīng)過有經(jīng)驗后自己去重新走過,前路慢慢,一...
    奮斗中前進(jìn)閱讀 209評論 0 0
  • 我是2017屆本科中文系畢業(yè)的應(yīng)屆畢業(yè)生,在校期間做過一些兼職,時間最久的就是家教,也是這份家教兼職,讓我更加明確...
    缺心璞玉閱讀 1,367評論 0 1