UICollectionView詳解(一)—— 基本使用

UICollectionView在目前的iOS開發(fā)中,使用非常廣泛懦胞,它可以完成許多UITableView完成不了的復(fù)雜的布局替久,在使用上,兩者也有著許多的相似之處躏尉,主要體現(xiàn)在布局的樣式上蚯根,UITableView主要有兩種布局:plain和group,而UICollectionView則可以根據(jù)我們的需要自定義各種各樣復(fù)雜的布局胀糜,這也是下面我們就UICollectionView的使用進(jìn)行一下詳細(xì)的解析颅拦。

基本使用方法

與UITableView相似,在UICollectionView時(shí)教藻,也要遵循數(shù)據(jù)源(UICollectionViewDataSource)與代理協(xié)議方法(UICollectionViewDelegate)距帅,也要注冊(cè)cell片排,與UITableView不同的是纺座,我們還需要為UICollectionView創(chuàng)建一個(gè)布局參數(shù),也就是UICollectionViewFlowLayout艳悔,這也是UICollectionView的精髓所在悄窃,正是通過它讥电,我們才實(shí)現(xiàn)了UICollectionView各式各樣的布局,這我們?cè)诤竺鏁?huì)一一講述轧抗,有興趣的同學(xué)也可以看一下蘋果官方文檔恩敌。
系統(tǒng)為我們提供了兩個(gè)UICollectionView的布局類:UICollectionViewLayout和UICollectionViewFlowLayout,UICollectionViewLayout類是一個(gè)抽象類横媚,我們?cè)谧远x布局的時(shí)候可以繼承此類纠炮,并在此基礎(chǔ)上設(shè)置布局信息,UICollectionViewFlowLayout繼承于UICollectionViewLayout分唾,是系統(tǒng)為我們寫好的布局類,該類為我們提供了一個(gè)簡(jiǎn)單的布局樣式狮斗,假如我們只需要一個(gè)特別簡(jiǎn)單的網(wǎng)格布局或者流水布局绽乔,可以直接使用它。

創(chuàng)建UICollectionView的基本代碼如下:

初始化

    /**
     創(chuàng)建layout
     */
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    /**
     創(chuàng)建collectionView
     */
    UICollectionView* collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor cyanColor];
    /**
     注冊(cè)item和區(qū)頭視圖碳褒、區(qū)尾視圖
     */
    [collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCollectionViewHeaderView"];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MyCollectionViewFooterView"];
    [self.view addSubview:collectionView];

實(shí)現(xiàn)協(xié)議方法

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
/**
 分區(qū)個(gè)數(shù)
 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
/**
 每個(gè)分區(qū)item的個(gè)數(shù)
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imagesArray.count;
}
/**
 創(chuàng)建cell
 */
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"MyCollectionViewCell";
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
    cell.imageStr = _imagesArray[indexPath.item];
    return cell;
}
/**
 創(chuàng)建區(qū)頭視圖和區(qū)尾視圖
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewHeaderView" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor yellowColor];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:headerView.bounds];
        titleLabel.text = [NSString stringWithFormat:@"第%ld個(gè)分區(qū)的區(qū)頭",indexPath.section];
        [headerView addSubview:titleLabel];
        return headerView;
    }else if(kind == UICollectionElementKindSectionFooter){
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewFooterView" forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor blueColor];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:footerView.bounds];
        titleLabel.text = [NSString stringWithFormat:@"第%ld個(gè)分區(qū)的區(qū)尾",indexPath.section];
        [footerView addSubview:titleLabel];
        return footerView;
    }
    return nil;
    
    
}
/**
 點(diǎn)擊某個(gè)cell
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"點(diǎn)擊了第%ld分item",(long)indexPath.item);
}
/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemW = (kScreenWidth-(kLineNum+1)*kLineSpacing)/kLineNum-0.001;
    return CGSizeMake(itemW, itemW);
}
/**
 每個(gè)分區(qū)的內(nèi)邊距(上左下右)
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(kLineSpacing, kLineSpacing, kLineSpacing, kLineSpacing);
}
/**
 分區(qū)內(nèi)cell之間的最小行間距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return kLineSpacing;
}
/**
 分區(qū)內(nèi)cell之間的最小列間距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return kLineSpacing;
}
/**
 區(qū)頭大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenWidth, 65);
}
/**
 區(qū)尾大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(kScreenWidth, 65);
}

最終的效果圖如下:


Simulator Screen Shot.png

上面我們提到了折砸,UICollectionViewFlowLayout是系統(tǒng)為我們提供的一個(gè)簡(jiǎn)單的流水布局,那么我們?cè)谥苯邮褂盟龊?jiǎn)單的布局時(shí)沙峻,可以直接設(shè)置它的一個(gè)屬性睦授,來達(dá)到我們布局的目的,這樣就可以省略掉一些UICollectionView協(xié)議方法的實(shí)現(xiàn)摔寨。
我們來看一下UICollectionViewFlowLayout都有哪些屬性可以設(shè)置:


UICollectionViewFlowLayout屬性.png

和上面我們實(shí)現(xiàn)的UICollectionView中的一些協(xié)議方法的名字非常相似去枷,根據(jù)名字應(yīng)該可以一一對(duì)應(yīng)。
那么,使用UICollectionViewFlowLayout的屬性設(shè)置布局的效果如果呢删顶,我們來看:

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

/**
     創(chuàng)建layout
     */
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    /**
     設(shè)置item的行間距和列間距
     */
    layout.minimumInteritemSpacing = kLineSpacing;
    layout.minimumLineSpacing = kLineSpacing;
    /**
     設(shè)置item的大小
     */
    CGFloat itemW = (kScreenWidth-(kLineNum+1)*kLineSpacing)/kLineNum-0.001;
    layout.itemSize = CGSizeMake(itemW, itemW);
    /*
     設(shè)置每個(gè)分區(qū)的上左下右的內(nèi)邊距
     */
    layout.sectionInset = UIEdgeInsetsMake(kLineSpacing, kLineSpacing,kLineSpacing, kLineSpacing);
    /**
     設(shè)置區(qū)頭和區(qū)尾的大小
     */
    layout.headerReferenceSize = CGSizeMake(kScreenWidth, 65);
    layout.footerReferenceSize = CGSizeMake(kScreenWidth, 65);
    /**
     設(shè)置分區(qū)的頭視圖和尾視圖是否始終固定在屏幕上邊和下邊
     */
    layout.sectionFootersPinToVisibleBounds = YES;
    /**
     創(chuàng)建collectionView
     */
    UICollectionView* collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor cyanColor];
    [collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCollectionViewHeaderView"];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MyCollectionViewFooterView"];
    [self.view addSubview:collectionView];
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imagesArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"MyCollectionViewCell";
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
    cell.imageStr = _imagesArray[indexPath.item];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewHeaderView" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor yellowColor];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:headerView.bounds];
        titleLabel.text = [NSString stringWithFormat:@"第%ld個(gè)分區(qū)的區(qū)頭",indexPath.section];
        [headerView addSubview:titleLabel];
        return headerView;
    }else if(kind == UICollectionElementKindSectionFooter){
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewFooterView" forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor blueColor];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:footerView.bounds];
        titleLabel.text = [NSString stringWithFormat:@"第%ld個(gè)分區(qū)的區(qū)尾",indexPath.section];
        [footerView addSubview:titleLabel];
        return footerView;
    }
    return nil;
    
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"點(diǎn)擊了第%ld分item",(long)indexPath.item);
}

效果圖:


Simulator Screen Shot .png

事實(shí)證明竖螃,兩種方法在實(shí)現(xiàn)的效果上并沒有任何區(qū)別。

總結(jié)

關(guān)于UICollectionView的基本使用大概就是這些內(nèi)容逗余,但是這些只適用于一些簡(jiǎn)單的網(wǎng)格或流水布局特咆,如果遇到比較復(fù)雜的布局,比如瀑布流等录粱,就需要自定義UICollectionViewLayout來布局了腻格。在下一篇文章中,我們會(huì)詳細(xì)介紹如何使用自定義UICollectionViewLayout來編寫復(fù)雜布局啥繁。

在下一篇文章中菜职,我將為大家介紹如何使用自定的UICollectionViewLayout來實(shí)現(xiàn)復(fù)雜的布局。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末输虱,一起剝皮案震驚了整個(gè)濱河市些楣,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌宪睹,老刑警劉巖愁茁,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異亭病,居然都是意外死亡鹅很,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門罪帖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來促煮,“玉大人,你說我怎么就攤上這事整袁〔こ荩” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵坐昙,是天一觀的道長(zhǎng)绳匀。 經(jīng)常有香客問我,道長(zhǎng)炸客,這世上最難降的妖魔是什么疾棵? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮痹仙,結(jié)果婚禮上是尔,老公的妹妹穿的比我還像新娘。我一直安慰自己开仰,他們只是感情好拟枚,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布薪铜。 她就那樣靜靜地躺著,像睡著了一般梨州。 火紅的嫁衣襯著肌膚如雪痕囱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天暴匠,我揣著相機(jī)與錄音鞍恢,去河邊找鬼。 笑死每窖,一個(gè)胖子當(dāng)著我的面吹牛帮掉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播窒典,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蟆炊,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了瀑志?” 一聲冷哼從身側(cè)響起涩搓,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎劈猪,沒想到半個(gè)月后昧甘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡战得,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年充边,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片常侦。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡浇冰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出聋亡,到底是詐尸還是另有隱情肘习,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布坡倔,位于F島的核電站漂佩,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏致讥。R本人自食惡果不足惜仅仆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一器赞、第九天 我趴在偏房一處隱蔽的房頂上張望垢袱。 院中可真熱鬧,春花似錦港柜、人聲如沸请契。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)爽锥。三九已至涌韩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間氯夷,已是汗流浹背臣樱。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腮考,地道東北人雇毫。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像踩蔚,于是被迫代替她去往敵國(guó)和親棚放。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

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