UICollectionView浅谈--简单实现集合视图

在iOS开发中,很多时候只用TableView来布局会很局促,而iOS6之后,Apple给开发者提供了UICollectionView来满足多样的布局方式,让我们在开发时不用只局限于TableView,更加自由,随心所欲.
在使用CollectionView时,你会发现其开发思路,与TableView有很多类似,下面我们就详细介绍下其简单的使用方法,以及实现一个简单的集合视图.

就像TableView在使用时要遵循UITableViewDataSource和UITableViewDataSource协议一样,在使用CollectionView时我们也要遵循UICollectionViewDataSource以及UICollectionViewDelegate,但需要注意的是,CollectionView比TableView多一个专门布局的UICollectionViewDelegateFlowLayout协议需要遵循.

UICollectionViewDataSource协议里有两个必须要实现的方法:

// 设置分区Cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;

// 设置Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

在创建CollectionView之前需要先创建UICollectionViewFlowLayout对象,且对于布局的设置,需要通过设置FlowLayout对象的属性来实现.
创建UICollectionViewFlowLayout对象,并设置其属性,代码如下:

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    // 最小行间距
    flowLayout.minimumLineSpacing = 10;
    // 最小列间距
    flowLayout.minimumInteritemSpacing = 10;
    // item尺寸
    flowLayout.itemSize = CGSizeMake(80, 50);

接下来就可以根据flowLayout创建UICollectionView对象,代码如下:

NSString *identifier = @"ColectionViewCellIdentifier";

    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    // 注册
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];

    [self.view addSubview:collectionView];

下面列举一些常用的代理方法:

// 设置分区内视图个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return arc4random()%12;
}

// 设置视图cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    
    return cell;
}

// 设置分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 10;
}

// 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld---%ld",indexPath.section,indexPath.row);
}

// 指定哪些路径可以被点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }else{
        return YES;
    }
}

// 设置视图内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

在设置CollectionView的HeaderView和FooterView时,其方法与TableView不同,需要用CollectionView增补视图来设置.
新建一个继承自UICollectionReusableView的类HeaderCollectionReusableView.(这里只介绍HeaderView设置方法,FooterView类似).
在HeaderCollectionReusableView.h中声明属性titleLb:

@property (nonatomic, strong) UILabel *titleLb;

并在HeaderCollectionReusableView.m中写增补视图初始化代码:

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLb = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 314, 30)];
        _titleLb.backgroundColor = [UIColor whiteColor];
        [self addSubview:_titleLb];
    }
    return self;
}

在CollectionView中注册增补视图HeaderCollectionReusableView:

NSString *headerIdentifier = @"CollectionViewHeaderViewIdentifier";

    // 注册Header增补视图
    [collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];

UICollectionViewDataSource提供了返回增补视图的方法:

// 返回增补视图�
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 这里指定的Header,如果指定Footer可以选择UICollectionElementKindSectionFooter
    if (kind == UIC
![3095EABD-A735-44D2-87F4-292C5805EFDC.png](http://upload-images.jianshu.io/upload_images/1421825-c809cc31a8ba9e3e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
ollectionElementKindSectionHeader) {
        
        HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor orangeColor];
        
        headerView.titleLb.text = @"HeaderView";
        
        return headerView;
    }
    return nil;
}

这样头视图就设置成功了, 运行结果如下图:

截图.jpg

下面附上完整代码:

#import "ViewController.h"
#import "HeaderCollectionReusableView.h"

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@end

NSString *identifier = @"ColectionViewCellIdentifier";
NSString *headerIdentifier = @"CollectionViewHeaderViewIdentifier";

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    // 最小行间距
    flowLayout.minimumLineSpacing = 10;
    // 最小列间距
    flowLayout.minimumInteritemSpacing = 10;
    // item尺寸
    flowLayout.itemSize = CGSizeMake(80, 50);
    // 头视图尺寸
    flowLayout.headerReferenceSize = CGSizeMake(100, 50);
    
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    // 注册
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];
    
    
    // 增补视图:可以通过新建View来自定义,但需要单独注册,且需要通过UICollectionViewDataSource中的代理方法:(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath设置.
    // 注册增补视图
    // header视图
    [collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
    

    [self.view addSubview:collectionView];
    
}

#pragma mark --- 代理方法

// 设置分区内视图个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return arc4random()%12;
}

// 设置视图cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    
    return cell;
}

// 设置分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 10;
}

// 返回增补视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 这里指定的Header,如果指定Footer可以选择UICollectionElementKindSectionFooter
    if (kind == UICollectionElementKindSectionHeader) {
        
        //从重用池里面取
        HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor orangeColor];
        
        headerView.titleLb.text = @"HeaderView";
        
        return headerView;
    }
    return nil;
}

// 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld---%ld",indexPath.section,indexPath.row);
}

// 指定哪些路径可以被点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }else{
        return YES;
    }
}

// 设置视图内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

HeaderCollectionReusableView.h

#import <UIKit/UIKit.h>

@interface HeaderCollectionReusableView : UICollectionReusableView

@property (nonatomic, strong) UILabel *titleLb;

@end

HeaderCollectionReusableView.m

#import "HeaderCollectionReusableView.h"

@implementation HeaderCollectionReusableView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLb = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 314, 30)];
        _titleLb.backgroundColor = [UIColor whiteColor];
        [self addSubview:_titleLb];
    }
    return self;
}

@end

我会持续更新iOS教程,喜欢就关注下啦~~~~~~~_

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容