iOS UICollectionViewController基本使用方法和简单的相册实现

来源:互联网 发布:小浪底水利枢纽知乎 编辑:程序博客网 时间:2024/05/29 14:55

最近项目需要写了一个相册

长相如图

那就简单记录一下实现。

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;}






0 0
原创粉丝点击