(转) iOS开发之UICollectionViewController系列(二) :详解CollectionView各种回调

UICollectionView的布局是可以自己定义的,在这篇博客中先在上篇博客的基础上进行扩充,我们先使用UICollectionViewFlowLayout,然后好好的介绍一下UICollectionView的一些回调方法,主要包括UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate相关回调方法,并通过实例来介绍每个回调的用法。并且给每个Section添加定制的Header和Footer,好废话少说进入今天的正题。
一、Demo总览
下图是本篇博客中Demo的最终运行效果,下面是我们要做的事情:

  1. 给每个Section添加自定义的重用Header和Footer
    2.调整第一个Section的上左下右的边距(UIEdgeInsets)
    3.给UICollectioinView设置多选
    4.处理Cell的高亮事件
    5.处理Cell的选中事件
    6.调整Cell的上下左右边距
    7.对Cell进行编辑



    二、UICollectionViewDataSource介绍
    1、在UICollectionViewDataSource回调方法中有一个返回Section数量的方法,如下所示,该方法和UITableView中的用法一致。在这儿我们返回5个Section,如下所示:

Objective-C

 #pragma mark 
 
 /**
  * 返回Section的个数
  */
 - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
     return 5;
 }

2、在UICollectionViewDataSource的回调方法中,还有一个是返回每个Section中Cell的数量的方法,在这我们返回30个Cell, 如下代码所示:

Objective-C

 /**
  * 返回每个Section中Cell的个数
  */
 - (NSInteger)collectionView: (UICollectionView *)collectionView
      numberOfItemsInSection: (NSInteger)section {
 
     return 30;
 }

3、在UICollectionViewDataSource还有一个必须实现的方法, 就是选择我们CollectionView中所使用的Cell, 在这里我们所使用的Cell是在Storyboard上实现的,所以不需要在我们的代码中注册Cell, 之间使用重用标示符就可以获取Cell的对象,如下所示:

Objective-C

  /**
   * 返回Cell种类
   */
  - (UICollectionViewCell *)collectionView: (UICollectionView *)collectionView
                    cellForItemAtIndexPath: (NSIndexPath *)indexPath {
 
      //通过Cell重用标示符来获取Cell
      CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: reuseIdentifier
                                                                           forIndexPath: indexPath];
 
     return cell;
 }

4、在UICollectionViewDataSource方法中有一个可选的方法就是为我们的Section添加Supplementary View(追加视图),下面是添Supplementary View(追加视图)的步骤。在UICollectionView中的Section中我们可以为其增加Header View和Footer View, 也就是官方文档上提到的Supplementary View(追加视图)。追加视图是可以重用的,也就是UICollectionReusableView。我们可以创建两个UICollectionReusableView的子类,一个是Header View, 另一个是Footer View。
(1)创建UICollectionReusableView
追加视图可以在Storyboard上添加,然后设置重用标示符,在代码中使用即可。这里我们是从xib文件来加载的Supplementary View, 先创建两个UICollectionReusableView子类,在创建该子类的同时创建相应的xib文件,如下所示:



创建Header View和Footer View的UICollectionReusableView,创建后的文件目录如下:



(2) 因为我们是从xib文件中加载的UICollectionReusableView,所以需要在相应的UICollectionView上进行注册。如果你是使用的Storyboard, 只需要在Storyboard中指定重用标示符即可。下面的代码就是在ViewDidLoad中调用注册UICollectionReusableView的方法。

Objective-C

  /**
   * 注册Header和FooterView
   * 便于在UICollectionViewDataSource中使用
   */
  - (void) registerHeaderAndFooterView {
      //注册headerView
      //获取含有UICollectionReusableView的Nib文件。
      UINib *headerNib = [UINib nibWithNibName: @"CollectionHeaderReusableView"
                                        bundle: [NSBundle mainBundle]];
 
     //注册重用View
     [self.collectionView registerNib: headerNib
           forSupplementaryViewOfKind: UICollectionElementKindSectionHeader
                  withReuseIdentifier: @"CollectionHeaderReusableView"];
 
     //注册FooterView
     UINib *footerNib = [UINib nibWithNibName: @"CollectionFooterReusableView"
                                       bundle:[ NSBundle mainBundle]];
 
     [self.collectionView registerNib: footerNib
           forSupplementaryViewOfKind: UICollectionElementKindSectionFooter
                  withReuseIdentifier: @"CollectionFooterReusableView"];
 
 }

(3)在UICollectionViewDataSource中的设置Supplementary View的方法中通过Header View和Footer View的重用标示符来为我们的Section设置Supplementary View,具体代码如下所示:

Objective-C

  /**
   * 设置Setion的Header和Footer(Supplementary View)
   */
  - (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView
             viewForSupplementaryElementOfKind: (NSString *)kind
                                   atIndexPath: (NSIndexPath *)indexPath{
 
      //设置SectionHeader
      if ([kind isEqualToString: UICollectionElementKindSectionHeader]) {
 
         UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionHeaderReusableView" forIndexPath:indexPath];
 
         return view;
     }
 
     //设置SectionFooter
     UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CollectionFooterReusableView" forIndexPath:indexPath];
     return view;
 
 }

UICollectionViewDataSource中的四个方法在上面都进行了实现,UICollectionViewDataSource主要是负责加载数据源的,包括Section的个数,每个Section中Cell的个数,每个Section中Supplementary View的种类。
三.UICollectionViewDelegateFlowLayout回调实现
UICollectionViewDelegateFlowLayout主要是负责显示的,比如Secion的大小、边距,Cell的大小边距,headerView的大小已经FooterView的大小,都是在UICollectionViewDelegateFlowLayout的相应协议的方法来实现的。接下来详细的介绍一下UICollectionViewDelegateFlowLayout协议中的方法。
1.同一个Section中同一种Cell(通过同一个Cell重用标示符获取的对象)可以有不同的尺寸,下面的代码是给Cell定制尺寸。代码的具体意思是第一个Section中的所有Cell的尺寸是(50,50)。 其余的时(60,60)。

Objective-C

  #pragma mark  
  /**
   * 改变Cell的尺寸
   */
  - (CGSize)collectionView: (UICollectionView *)collectionView
                    layout: (UICollectionViewLayout*)collectionViewLayout
    sizeForItemAtIndexPath: (NSIndexPath *)indexPath{
 
      if (indexPath.section == 0) {
         return CGSizeMake(50, 50);
     }
 
     return CGSizeMake(60, 60);
 }

2.改变Section的上下左右边距–UIEdgeInsetsMake(上, 左, 下, 右),逆时针旋转。第一个Section的上左下右的边距都是50, 其余的Section上左下右的边距是0。具体实现看如下代码:

Objective-C

  /**
   * Section的上下左右边距--UIEdgeInsetsMake(上, 左, 下, 右);逆时针
   */
  - (UIEdgeInsets)collectionView: (UICollectionView *)collectionView
                          layout: (UICollectionViewLayout*)collectionViewLayout
          insetForSectionAtIndex: (NSInteger)section{
 
      if (section == 0) {
          return UIEdgeInsetsMake(50, 50, 50, 50);
     }
     return UIEdgeInsetsMake(0, 0, 0, 0);
 }

3.设置每个Cell的上下边距的回调如下所示,第一个Section的Cell上下边距是5.0f, 其余的为20.0f。

Objective-C

  /**
   * Section中每个Cell的上下边距
   */
  - (CGFloat)collectionView: (UICollectionView *)collectionView
                     layout: (UICollectionViewLayout*)collectionViewLayout
  minimumLineSpacingForSectionAtIndex: (NSInteger)section{
      if (section == 0) {
          return 5.0f;
      }
     return 20.0f;
 }

4.设置Cell的左右边距,第一个Section的Cell左右边距是5.0f, 其余的为20.0f。

Objective-C

  /**
   * Section中每个Cell的左右边距
   */
  - (CGFloat)collectionView: (UICollectionView *)collectionView
                     layout: (UICollectionViewLayout*)collectionViewLayout
  minimumInteritemSpacingForSectionAtIndex: (NSInteger)section{
      if (section == 0) {
          return 5.0f;
      }
     return 20.0f;
 }

5.设置Header View和Footer View的大小的回调如下。

Objective-C

  /**
   * headerView的大小
   */
  - (CGSize)collectionView: (UICollectionView *)collectionView
                    layout: (UICollectionViewLayout*)collectionViewLayout
  referenceSizeForHeaderInSection: (NSInteger)section{
      return CGSizeMake(200, 50);
  }
 
 /**
  * footerView的大小
  */
 - (CGSize)collectionView: (UICollectionView *)collectionView
                   layout: (UICollectionViewLayout*)collectionViewLayout
 referenceSizeForFooterInSection: (NSInteger)section{
     return CGSizeMake(200, 50);
 }

上面的方法就是UICollectionViewDelegateFlowLayout中所有的方法了,负责布局显示的。
四、UICollectionViewDelegate回调实现
UICollectionViewDelegate中的代理方法主要是负责Cell的交互的,比如是否高亮,是否选,是否可编辑等,接下来要为大家详细的介绍UICollectionViewDelegate中的代理方法。
1.为了这部分的效果展示,我们需要对Cell添加一些控件,并且设置其Highlight和Selected的一些状态。为Cell添加上ImageView, Cell的高亮状态和非高亮状态对应的ImageView上的图片是不同的。再添加一个Button, 并为Button设置Selected和Default状态下的图片,Button的选中和默认状态由Cell的选中状态来定。Cell中改变ImageView的图片的代码如下所示,函数传入的参数是当前Cell的高亮状态,根据高亮状态来设置ImageView上的Image。(有的小伙伴会问为什么给ImageView在Default状态和Highlight下设置不同的图片,然后直接改变ImageView的高亮状态即可。你可以试一下,达不到预期的效果)

Objective-C

  - (void) changeHighLightWithBool: (BOOL) highlight{
 
      NSString *imageName = @"003.jpg";
 
      if (highlight) {
          imageName = @"002.jpg";
      }
 
      [_highlightImage setImage: [UIImage imageNamed:imageName]];
 }

2.设置Cell可以高亮, 返回YES代表Cell可以高亮,返回NO代表Cell不可高亮。高亮就是触摸Cell时该Cell变为高亮状态,在代码中的反应就是Cell的Highligth属性变为YES。而触摸结束时,Cell的Highligth属性就变为NO。

Objective-C

  #pragma mark
 
  /**
   * Cell是否可以高亮
   */
  - (BOOL)collectionView: (UICollectionView *)collectionView
  shouldHighlightItemAtIndexPath: (NSIndexPath *)indexPath{
 
      return YES;
 
 }

3.下面这个方法是自己写的,用来在界面上反应Cell的高亮状态。 ImageView在当前Cell高亮状态下和非高亮状态下所加载的图片不同,所以可以看出Cell高亮和非高亮。

Objective-C

  /**
   * 根据高亮状态修改背景图片
   */
  - (void) changeHighlightCellWithIndexPaht: (NSIndexPath *) indexPath{
      //获取当前变化的Cell
      CollectionViewCell *currentHighlightCell = (CollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
 
      [currentHighlightCell changeHighLightWithBool:currentHighlightCell.highlighted];
 
     if (currentHighlightCell.highlighted == YES){
 
         NSLog(@"第%ld个Section上第%ld个Cell变为高亮",indexPath.section ,indexPath.row);
         return;
     }
 
     if (currentHighlightCell.highlighted == NO){
         NSLog(@"第%ld个Section上第%ld个Cell变为非高亮",indexPath.section ,indexPath.row);
     }
 
 }

4.Cell从非高亮变为高亮状态时回调用下面的方法,为了反映Cell的高亮状态,我们去改变一下Cell上ImageView的图片。

Objective-C


  /**
   * 如果Cell可以高亮,Cell变为高亮后调用该方法
   */
  - (void)collectionView: (UICollectionView *)collectionView
  didHighlightItemAtIndexPath: (NSIndexPath *)indexPath{
 
      [self changeHighlightCellWithIndexPath:indexPath];
  }
 
 /**
  * 如果Cell可以高亮,Cell从高亮变为非高亮调用该方法
  */
 - (void)collectionView: (UICollectionView *)collectionView
 didUnhighlightItemAtIndexPath: (NSIndexPath *)indexPath{
 
     [self changeHighlightCellWithIndexPath:indexPath];
 
 }

5.设定Cell是否可选的回调如下所示,Cell被选中时该Cell的Selected为YES, 取消选中Selected为NO;

Objective-C

 /**
  * Cell是否可以选中
  */
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
     return YES;
 }
  1. 如果想让你的Cell支持多选,就需要设定一下CollectionView的allowsMultipleSelection属性,下面的代码是在ViewDidLoad中添加的,如下所示:

Objective-C

     //设置Cell多选
     self.collectionView.allowsMultipleSelection = YES;

7.如果在多选状态下需要支持取消Cell的多选,那么就去执行下面的方法,并返回YES。就是支持在多选状态下取消选中状态。

Objective-C

 /**
  * Cell多选时是否支持取消功能
  */
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
     return YES;
 }

8.下面这个方法是自己封装的,用来根据Cell的选中状态来改变Cell上Button的选中状态,具体代码实现如下:

Objective-C

  /**
   * Cell根据Cell选中状态来改变Cell上Button按钮的状态
   */
  - (void) changeSelectStateWithIndexPath: (NSIndexPath *) indexPath{
      //获取当前变化的Cell
      CollectionViewCell *currentSelecteCell = (CollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
 
      currentSelecteCell.selectButton.selected = currentSelecteCell.selected;
 
     if (currentSelecteCell.selected == YES){
         NSLog(@"第%ld个Section上第%ld个Cell被选中了",indexPath.section ,indexPath.row);
         return;
     }
 
     if (currentSelecteCell.selected == NO){
         //NSLog(@"第%ld个Section上第%ld个Cell取消选中",indexPath.section ,indexPath.row);
     }
 
 }

9.在Cell选中和取消选中时都会调用上面的方法来改变Button的选中状态,下面是Cell在选中时以及取消选中时所调用的方法:

Objective-C

  /**
   * Cell选中调用该方法
   */
  - (void)collectionView: (UICollectionView *)collectionView
  didSelectItemAtIndexPath: (NSIndexPath *)indexPath{
 
      [self changeSelectStateWithIndexPath:indexPath];
  }
 
 /**
  * Cell取消选中调用该方法
  */
 - (void)collectionView: (UICollectionView *)collectionView didDeselectItemAtIndexPath: (NSIndexPath *)indexPath{
 
     [self changeSelectStateWithIndexPath:indexPath];
 }

10.下方四个方法是Cell将要出现,Cell出现后,Supplementary View将要出现以及Supplementary View已经出现所调用的方法,具体信息请看下方代码实现:

Objective-C

  /**
   * Cell将要出现的时候调用该方法
   */
  - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0){
      NSLog(@"第%ld个Section上第%ld个Cell将要出现",indexPath.section ,indexPath.row);
  }
 
  /**
   * Cell出现后调用该方法
  */
 - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
     NSLog(@"第%ld个Section上第%ld个Cell已经出现",indexPath.section ,indexPath.row);
 }
 
 /**
  * headerView或者footerView将要出现的时候调用该方法
  */
 - (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0){
 
     NSLog(@"第%ld个Section上第%ld个扩展View将要出现",indexPath.section ,indexPath.row);
 
 }
 
 /**
  * headerView或者footerView出现后调用该方法
  */
 - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
 
     NSLog(@"第%ld个Section上第%ld个扩展View已经出现",indexPath.section ,indexPath.row);
 
 }

在UICollectionViewDelegate回调方法中还有三个回调方法是关于Cell编辑的,比如copy, past, cut等操作,具体代码就不在此赘述了。在Demo中给出了实现方式,主要涉及到UIPasteboard的操作,本篇博客的整体的Demo回分享到Github上,下方是Github上的分享链接,感兴趣的小伙伴可以进行Clone。

Github链接

参考文章:iOS开发之窥探UICollectionViewController(二) :详解CollectionView各种回调

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

推荐阅读更多精彩内容

  • Swift版本点击这里欢迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh阅读 24,839评论 7 249
  • 最近将 UICollectionView 进行了一个全面的学习及总结,参考了网上大量的文章,把官方文档进行了大概翻...
    varlarzh阅读 20,419评论 3 94
  • 概述 UICollectionView是iOS开发中最常用的UI控件之一,可以用它来管理一组有序的不同尺寸的视图,...
    渐z阅读 2,863评论 0 3
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,595评论 4 59
  • 记住吧:只有一个时间是重要的,那就是现在!它之所以如此重要,是因为它是我们有所作为的时间。 ——列夫 • 尼古拉耶...
    少校了悟阅读 2,056评论 0 2