UICollectionView是iOS 6中引進的列表展示控件,用於展現集合視圖,佈局更加靈活,能夠高度定製內容的展示,能夠有效的進行數據管理,即便對於大量數據,也很是的高效。蘋果官方給出了Demo點我下載是一個相似於Android裏面的GridView的實現。和UITableView的實現相比較,他對於每個Item都是一次複用,而UITableView只能對於每一行進行復用。若是你認爲它僅僅是對GridView在IOS中的實現的話,那你就過小看它的功能了。下面咱們就來一塊兒學習UICollectionView的使用方法。html
網上有一個書架的舉例很經典,很好的說明了UICollectionView的表現形式。如圖:面試
一個標準的UICollectionView包含三個部分,他們都是UIView的子類:網絡
Cells 用於展現內容的主體,對於不一樣的Cell能夠指定不一樣的尺寸和內容。
Supplementary Views 附加視圖,能夠理解爲UITableView每一個Section的HeaderView和FooterView。
Decoration Views 裝飾視圖,這是每一個section的背景視圖,用於裝飾該section。
將上圖分解爲以上三個元素組成的結構,以下圖所示: app
UICollectionView 向 UICollectionViewLayout 詢問佈局,當詢問過程發生時,layout 對象會建立 UICollectionViewLayoutAttributes 實例。一個 UICollectionViewLayoutAttributes 對象管理着一個對應的 item layout 相關信息(一對一關係)佈局
效果以下: 學習
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH/2-10, SCREEN_WIDTH/2-10); flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; flowLayout.minimumLineSpacing = 20;//設置每一個item之間的間距
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.navBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-self.navBarHeight) collectionViewLayout:flowLayout]; collectionView.delegate = self; collectionView.dataSource = self; collectionView.showsVerticalScrollIndicator = YES; collectionView.backgroundColor = [UIColor blackColor]; [self.view addSubview:collectionView];
首先在初始化的時候註冊cell的Id。ui
[self.collectionView registerClass:[Demo1Cell class] forCellWithReuseIdentifier:Demo1CellID];
而後在使用Cell的時候,使用如下方法進行重用。spa
Demo1Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Demo1CellID forIndexPath:indexPath];
#pragma mark- UICollectionViewDataSource -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return 31; } -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ Demo1Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:Demo1CellID forIndexPath:indexPath]; if(!cell){ cell = [[Demo1Cell alloc] init]; } [cell setImageName:[NSString stringWithFormat:@"%zi",indexPath.row] content:[NSString stringWithFormat:@"{%zi,%zi}",indexPath.section,indexPath.row]]; return cell; }
推薦一個iOS高級交流羣:624212887,羣文件自行下載,無論你是小白仍是大牛熱烈歡迎進羣 ,分享面試經驗,討論技術, 你們一塊兒交流學習成長!但願幫助開發者少走彎路。——點擊:加入
若是以爲對你還有些用,就關注小編+喜歡這一篇文章。你的支持是我繼續的動力。代理
下篇文章預告:使用UICollectionView實現一個無限輪播的案例
code
文章來源於網絡,若有侵權,請聯繫小編刪除。