从零开始UICollectionView(1)--基本实现

UICollectionView简介

NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionView : UIScrollView

打开UICollectionView的.h文件可以发现,UIcollectionView自iOS6以后加入UIKit框架的,它跟UITableView一样继承自UIScrollView。所以在目前市场上所有版本的iPhone上,基本都能支持使用UICollectionView。而且在对数据的展示和UI的构建上,UICollectionView也甩出UITableView十八条街。

UICollectionView的实现说简单挺简单的,无非也就是两个代理和数据源的配合,比UITableView略微复杂的就是有一个需要继承自UICollectionViewLayout的布局信息。
但是说复杂也能很复杂,包括整个UICollectionView的定制布局(瀑布流等)和布局动画以及插入删除item时的动画,也是一个值得深究的控件。

本章主要是简略的实现一个有头视图、尾视图和展示视图的纵向UICollectionView。更为复杂的定制布局我们会在以后的章节详细展开。

1.先说说 Layout

NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionViewLayout : NSObject <NSCoding>

所有关于UICollectionView的精髓,几乎都在这个类上面,它基本确定了整个UICollectionView的布局信息甚至包括一些动画效果,但是定制它是一个问题,而且它是一个抽像类,不能直接被使用,需要定义一个继承自它的子类,然后来徐徐展开。
但是Apple官方给我们已经定制好了一个类 : UICollectionViewFlowLayout ,这个类继承自UICollectionViewLayout,并且定制好了代理方法来方便我们控制UICollectionView的布局,但是也仅仅限制于网格布局。
下面我们就是用UICollectionViewFlowLayout来写我们的简易UICollectionView Demo。

2.代码开撸

2.1 先写基本代码,兵马未动粮草先行,我们先构建一个模拟的数据源数组,再创建一个UICollectionView,关联上UICollectionViewFlowLayout的对象,设置代理,注册好Cell和Header、Footer的信息。
//数据源
-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSArray alloc] init];
    
        NSMutableArray * theArray = [NSMutableArray array];
        for (NSInteger index = 0; index < 3; index++) {
            NSMutableArray * subArray = [NSMutableArray array];
            for (NSInteger indexJ = 0; indexJ < 10; indexJ++) {
                MainModel * model = [MainModel new];
                model.indexStr = [NSString stringWithFormat:@"%ld-%ld",index,indexJ];
                [subArray addObject:model];
            }
            [theArray addObject:[NSArray arrayWithArray:subArray]];
        }
    
        _dataArray = [NSArray arrayWithArray:theArray];
    }

    return _dataArray;
}
//UICollectionView视图
-(UICollectionView *)mainCollectionView
{
    if (!_mainCollectionView) {
        UICollectionViewFlowLayout * layout =     [UICollectionViewFlowLayout new];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.sectionHeadersPinToVisibleBounds = NO;//头部视图悬停设为YES
      layout.sectionFootersPinToVisibleBounds = NO;//尾部视图悬停设为YES
    
      _mainCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
      _mainCollectionView.backgroundColor = [UIColor whiteColor];
      _mainCollectionView.delegate = self;
      _mainCollectionView.dataSource = self;
    
      [_mainCollectionView registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier:[MainCollectionViewCell reuseIdentifier]];
      [_mainCollectionView registerClass:[MainCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[MainCollectionHeaderView reuseIdentifier]];
      [_mainCollectionView registerClass:[MainCollectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:[MainCollectionFooterView reuseIdentifier]];
    }

return _mainCollectionView;
 }
2.2 然后我们添加代理,这里我们通过代理的方式控制布局,这样更易于我们的操控。

UICollectionViewDelegate:主要管理于用户交互方面
UICollectionViewDataSource:主要管理视图数据源方面
UICollectionViewDelegateFlowLayout:主要管理布局信息方面

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
UICollectionView Data Source methods (代理里面还有许多方法,我们主要展示最关键的几个)
//返回多少个组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView   *)collectionView
{
    return self.dataArray.count;
}
//返回每组多少个视图
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray * subArray = self.dataArray[section];
    return subArray.count;
}
//返回视图的具体事例,我们的数据关联就是放在这里
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MainCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MainCollectionViewCell reuseIdentifier] forIndexPath:indexPath];

    cell.backgroundColor = [UIColor orangeColor];
    cell.contentView.frame = cell.bounds;
    cell.backgroundColor = [UIColor lightGrayColor];

    MainModel * model = self.dataArray[indexPath.section][indexPath.row];

    cell.title = model.indexStr;

    return cell;
}
UICollectionView Delegate method (代理里面还有许多方法,我们主要展示最关键的几个)
//选中某个 item 触发
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选中 : %ld--%ld",indexPath.section,indexPath.item);
}

//取消某个 item 触发
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"取消选中 : %ld--%ld",indexPath.section,indexPath.item);
}
UICollectionView Delegate FlowLayout method (代理里面还有许多方法,我们主要展示最关键的几个)
// cell 尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.view.bounds.size.width-5-5-10*2)/3.0, 50);
}

// 装载内容 cell 的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

//最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}

//item最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}

//头视图尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.bounds.size.width, 50);
}

//尾视图尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(self.view.bounds.size.width, 50);
}
2.3 最后是我们的实现效果:
纵向效果

上图是纵向效果,如果需要横向,则改一下UICollectionViewFlowLayoutscrollDirection属性即可,当然啦,尺寸各方面需要再细细调节,简单的很,就需要各位看官慢慢探索了。


3.下节预告,我们将依托UICollectionView来做一个自由移动Cell的关键字选框。效果如下:
自由移动Cell

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 3,723评论 1 22
  • 半夜,醒来 纠结绝句的面目 朵云浮,朵云黄...... 一个羽雁天上 一个虚无手中 渺渺字迹,或沉、或浮 清水清,...
    风居阅读 428评论 0 1
  • 三天后,方正、林玥、郑广坤和张志刚四人再次聚首于张志刚的办公室中,张志刚兴冲冲地掏出一样银行卡递给方正说道 :“想...
    长白居士阅读 374评论 0 0
  • 去年,我一个人在北京过年,那是第一次没有回家过年。 今年,我买了一张农历二十九到家的火车票,爸妈说要等我回家吃年夜...
    天野丢阅读 285评论 2 1