天天看點

iOS UICollectionViewController基本使用方法和簡單的相冊實作

最近項目需要寫了一個相冊

長相如圖

iOS UICollectionViewController基本使用方法和簡單的相冊實作

那就簡單記錄一下實作。

1、首先建立一個controller繼承 UICollectionViewController;

在viewdid函數裡面設定一下北京,因為 UICollectionViewController 的預設背景為黑色,

- (void)viewDidLoad {
    [super viewDidLoad];
    //設定collection背景
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
}
           

2、設定相冊的section(用字典來儲存相冊資料,以時間為key,每個key下儲存image資料)

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return [self.photoCollectionsDictionary count];
}
           

3、設定cell的個數(當每個section下的cell數量)

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return [ [self.photoCollectionsDictionary objectForKey:[keys objectAtIndex:section]] count]
}
           

4、設定每個cell PhotoCollectionsCellView 是自定的cell,繼承自UICollectionViewCell,并在PhotoCollectionsCellView添加需要的圖檔

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoCollectionsCellView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellView" forIndexPath:indexPath];
   UIImage * image = [UIImage imageNamed:@"test.JEPG"];
   [cell.imageView setImage:image];
    return cell;
}
           

5、點選每個cell的調用函數

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//可以寫出點選時候需要的處理
  }
           

6、設定分類的的頭和底部PhotoCollectionsHeaderView 是我自定義的頭部 其中設定了title ,但是要記得加上<UIcollectionViewDataSource >

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    //設定相冊分類的頭部
    if (kind == UICollectionElementKindSectionHeader){
        
        PhotoCollectionsHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    
        headerView.title.text = [keys objectAtIndex:indexPath.section];

        reusableview = headerView;
        
    }
    if (kind == UICollectionElementKindSectionFooter){
        
        PhotoCollectionsHeaderView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        
        reusableview = footerview;  
    }  
    return reusableview;

}