先整體說一下,UICollectionView和 UICollectionViewController是iOS6新引進的,用于展示集合視圖,布局更加靈活,可實作多列布局,用法類似于UITableView和 UITableViewController。
之前一直用UITableView 和GridView,最近因項目需要,用了一把UICollectionView和 UICollectionViewController,幾點體會記錄并分享一下(使用環境:Xcode6.1、storyboard):
1、先說一個注意點:在storyboard中配置好CollectionCell後,不需要再注冊CollectionCell。
在storyboard中配置好CollectionCell後,使用類似下面的語句後,反而無法正常顯示cell了,
[self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
調試的時候,在cellForItemAtIndexPath中log出來發現 cell.nameLabel等自定義的控件全部為null,去掉那行注冊代碼後,世界馬上完美展現^^。
2、結合storyboard中對UICollectionView的相關配置,.m檔案中的最簡單實作最需要下面4個方法/協定(和 UITableView 太像了)。
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView //定義展示的Section的個數
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section //定義section裡展示的UICollectionViewCell的個數
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath //每個UICollectionView展示的内容
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath //UICollectionView被選中時調用的方法
3、如果要加頭部或尾部,用的是這個
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if (kind == UICollectionElementKindSectionFooter)
{
CollectionFooterView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CollectionFooterView" forIndexPath:indexPath];
reusableView.name_lab.text=group_name;
return reusableView;
}
return nil;
}
個人習慣,喜歡用xib和storyboard 哈^^。