iOS流布局UICollectionView系列一——初識(shí)與簡(jiǎn)單使用UICollectionView

目錄[-]
iOS流布局UICollectionView系列一——初識(shí)與簡(jiǎn)單使用UICollectionView
一、簡(jiǎn)介
二、先來實(shí)現(xiàn)一個(gè)最簡(jiǎn)單的九宮格類布局
三、UICollectionView中的常用方法和屬性
iOS流布局UICollectionView系列一——初識(shí)與簡(jiǎn)單使用UICollectionView

一、簡(jiǎn)介

    UICollectionView是iOS6之后引入的一個(gè)新的UI控件,它和UITableView有著諸多的相似之處,其中許多代理方法都十分類似。簡(jiǎn)單來說,UICollectionView是比UITbleView更加強(qiáng)大的一個(gè)UI控件,有如下幾個(gè)方面:

1、支持水平和垂直兩種方向的布局

2、通過layout配置方式進(jìn)行布局

3、類似于TableView中的cell特性外,CollectionView中的Item大小和位置可以自由定義

4、通過layout布局回調(diào)的代理方法,可以動(dòng)態(tài)的定制每個(gè)item的大小和collection的答題布局屬性

5、更加強(qiáng)大一點(diǎn),完全自定義一套layout布局方案,可以實(shí)現(xiàn)意想不到的效果

這篇博客,我們主要討論CollectionView使用原生layout的方法和相關(guān)屬性,其他特點(diǎn)和更強(qiáng)的制定化,會(huì)在后面的博客中介紹

二、先來實(shí)現(xiàn)一個(gè)最簡(jiǎn)單的九宮格類布局

    在了解UICollectionView的更多屬性前,我們先來使用其進(jìn)行一個(gè)最簡(jiǎn)單的流布局試試看,在controller的viewDidLoad中添加如下代碼:

//創(chuàng)建一個(gè)layout布局類
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
//設(shè)置布局方向?yàn)榇怪绷鞑季?layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//設(shè)置每個(gè)item的大小為100*100
layout.itemSize = CGSizeMake(100, 100);
//創(chuàng)建collectionView 通過一個(gè)布局策略layout來創(chuàng)建
UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
//代理設(shè)置
collect.delegate=self;
collect.dataSource=self;
//注冊(cè)item類型 這里使用系統(tǒng)的類型
[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];

[self.view addSubview:collect];

這里有一點(diǎn)需要注意,collectionView在完成代理回調(diào)前,必須注冊(cè)一個(gè)cell,類似如下:

[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
這和tableView有些類似,又有些不同,因?yàn)閠ableView除了注冊(cè)cell的方法外,還可以通過臨時(shí)創(chuàng)建來做:

//tableView在從復(fù)用池中取cell的時(shí)候,有如下兩種方法
//使用這種方式如果復(fù)用池中無,是可以返回nil的,我們?cè)谂R時(shí)創(chuàng)建即可

  • (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
    //6.0后使用如下的方法直接從注冊(cè)的cell類獲取創(chuàng)建,如果沒有注冊(cè) 會(huì)崩潰
  • (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
    我們可以分析:因?yàn)閁ICollectionView是iOS6.0之前的新類,因此這里統(tǒng)一了從復(fù)用池中獲取cell的方法,沒有再提供可以返回nil的方式,并且在UICollectionView的回調(diào)代理中,只能使用從復(fù)用池中獲取cell的方式進(jìn)行cell的返回,其他方式會(huì)崩潰,例如:

//這是正確的方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
return cell;
}

//這樣做會(huì)崩潰
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
// cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
UICollectionViewCell * cell = [[UICollectionViewCell alloc]init];
return cell;
}
上面錯(cuò)誤的方式會(huì)崩潰,信息如下,讓我們使用從復(fù)用池中取cell的方式:

上面的設(shè)置完成后,我們來實(shí)現(xiàn)如下幾個(gè)代理方法:

這里與TableView的回調(diào)方式十分類似

//返回分區(qū)個(gè)數(shù)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//返回每個(gè)分區(qū)的item個(gè)數(shù)
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
//返回每個(gè)item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
return cell;
}
效果如下:

同樣,如果內(nèi)容的大小超出一屏,和tableView類似是可以進(jìn)行視圖滑動(dòng)的。

還有一點(diǎn)細(xì)節(jié),我們?cè)谏厦嬖O(shè)置布局方式的時(shí)候設(shè)置了垂直布局:

layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//這個(gè)是水平布局
//layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
這樣系統(tǒng)會(huì)在一行充滿后進(jìn)行第二行的排列,如果設(shè)置為水平布局,則會(huì)在一列充滿后,進(jìn)行第二列的布局,這種方式也被稱為流式布局

三、UICollectionView中的常用方法和屬性

//通過一個(gè)布局策略初識(shí)化CollectionView

  • (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout;

//獲取和設(shè)置collection的layout
@property (nonatomic, strong) UICollectionViewLayout *collectionViewLayout;

//數(shù)據(jù)源和代理
@property (nonatomic, weak, nullable) id <UICollectionViewDelegate> delegate;
@property (nonatomic, weak, nullable) id <UICollectionViewDataSource> dataSource;

//從一個(gè)class或者xib文件進(jìn)行cell(item)的注冊(cè)

  • (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
  • (void)registerNib:(nullable UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;

//下面兩個(gè)方法與上面相似,這里注冊(cè)的是頭視圖或者尾視圖的類
//其中第二個(gè)參數(shù)是設(shè)置 頭視圖或者尾視圖 系統(tǒng)為我們定義好了這兩個(gè)字符串
//UIKIT_EXTERN NSString *const UICollectionElementKindSectionHeader NS_AVAILABLE_IOS(6_0);
//UIKIT_EXTERN NSString *const UICollectionElementKindSectionFooter NS_AVAILABLE_IOS(6_0);

  • (void)registerClass:(nullable Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
  • (void)registerNib:(nullable UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;

//這兩個(gè)方法是從復(fù)用池中取出cell或者頭尾視圖

  • (__kindof UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
  • (__kindof UICollectionReusableView *)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;

//設(shè)置是否允許選中 默認(rèn)yes
@property (nonatomic) BOOL allowsSelection;

//設(shè)置是否允許多選 默認(rèn)no
@property (nonatomic) BOOL allowsMultipleSelection;

//獲取所有選中的item的位置信息

  • (nullable NSArray<NSIndexPath *> *)indexPathsForSelectedItems;

//設(shè)置選中某一item,并使視圖滑動(dòng)到相應(yīng)位置,scrollPosition是滑動(dòng)位置的相關(guān)參數(shù),如下:
/*
typedef NS_OPTIONS(NSUInteger, UICollectionViewScrollPosition) {
//無
UICollectionViewScrollPositionNone = 0,
//垂直布局時(shí)使用的 對(duì)應(yīng)上中下
UICollectionViewScrollPositionTop = 1 << 0,
UICollectionViewScrollPositionCenteredVertically = 1 << 1,
UICollectionViewScrollPositionBottom = 1 << 2,
//水平布局時(shí)使用的 對(duì)應(yīng)左中右
UICollectionViewScrollPositionLeft = 1 << 3,
UICollectionViewScrollPositionCenteredHorizontally = 1 << 4,
UICollectionViewScrollPositionRight = 1 << 5
};
*/

  • (void)selectItemAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition;

//將某一item取消選中

  • (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;

//重新加載數(shù)據(jù)

  • (void)reloadData;

//下面這兩個(gè)方法,可以重新設(shè)置collection的布局,后面的方法多了一個(gè)布局完成后的回調(diào),iOS7后可以用
//使用這兩個(gè)方法可以產(chǎn)生非常炫酷的動(dòng)畫效果

  • (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated;
  • (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);

//下面這些方法更加強(qiáng)大,我們可以對(duì)布局更改后的動(dòng)畫進(jìn)行設(shè)置
//這個(gè)方法傳入一個(gè)布局策略layout,系統(tǒng)會(huì)開始進(jìn)行布局渲染,返回一個(gè)UICollectionViewTransitionLayout對(duì)象
//這個(gè)UICollectionViewTransitionLayout對(duì)象管理動(dòng)畫的相關(guān)屬性,我們可以進(jìn)行設(shè)置

  • (UICollectionViewTransitionLayout *)startInteractiveTransitionToCollectionViewLayout:(UICollectionViewLayout *)layout completion:(nullable UICollectionViewLayoutInteractiveTransitionCompletion)completion NS_AVAILABLE_IOS(7_0);
    //準(zhǔn)備好動(dòng)畫設(shè)置后,我們需要調(diào)用下面的方法進(jìn)行布局動(dòng)畫的展示,之后會(huì)調(diào)用上面方法的block回調(diào)
  • (void)finishInteractiveTransition NS_AVAILABLE_IOS(7_0);
    //調(diào)用這個(gè)方法取消上面的布局動(dòng)畫設(shè)置,之后也會(huì)進(jìn)行上面方法的block回調(diào)
  • (void)cancelInteractiveTransition NS_AVAILABLE_IOS(7_0);

//獲取分區(qū)數(shù)

  • (NSInteger)numberOfSections;

//獲取某一分區(qū)的item數(shù)

  • (NSInteger)numberOfItemsInSection:(NSInteger)section;

//下面兩個(gè)方法獲取item或者頭尾視圖的layout屬性,這個(gè)UICollectionViewLayoutAttributes對(duì)象
//存放著布局的相關(guān)數(shù)據(jù),可以用來做完全自定義布局,后面博客會(huì)介紹

  • (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
  • (nullable UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

//獲取某一點(diǎn)所在的indexpath位置

  • (nullable NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point;

//獲取某個(gè)cell所在的indexPath

  • (nullable NSIndexPath *)indexPathForCell:(UICollectionViewCell *)cell;

//根據(jù)indexPath獲取cell

  • (nullable UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath;

//獲取所有可見cell的數(shù)組

  • (NSArray<__kindof UICollectionViewCell *> *)visibleCells;

//獲取所有可見cell的位置數(shù)組

  • (NSArray<NSIndexPath *> *)indexPathsForVisibleItems;

//下面三個(gè)方法是iOS9中新添加的方法,用于獲取頭尾視圖

  • (UICollectionReusableView *)supplementaryViewForElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
  • (NSArray<UICollectionReusableView *> *)visibleSupplementaryViewsOfKind:(NSString *)elementKind NS_AVAILABLE_IOS(9_0);
  • (NSArray<NSIndexPath *> *)indexPathsForVisibleSupplementaryElementsOfKind:(NSString *)elementKind NS_AVAILABLE_IOS(9_0);

//使視圖滑動(dòng)到某一位置,可以帶動(dòng)畫效果

  • (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;

//下面這些方法用于動(dòng)態(tài)添加,刪除,移動(dòng)某些分區(qū)獲取items

  • (void)insertSections:(NSIndexSet *)sections;

  • (void)deleteSections:(NSIndexSet *)sections;

  • (void)reloadSections:(NSIndexSet *)sections;

  • (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection;

  • (void)insertItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

  • (void)deleteItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

  • (void)reloadItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

  • (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;

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

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