转载自:http://www.cnblogs.com/wayne23/p/4013522.html 

初始化部分:

UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 20, 250, 350) collectionViewLayout:flowLayout];
self.myCollectionView.backgroundColor = [UIColor grayColor];
[self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@“myCell"];
self.myCollectionView.delegate = self;
self.myCollectionView.dataSource = self; [self.view addSubview:self.myCollectionView];

UICollectionViewLayout

UICollectionViewLayout决定了UICollectionView如何显示在界面上,Apple提供了一个最简单的默认layout对象:UICollectionViewFlowLayout。

Flow Layout是一个Cells的线性布局方案,并具有页面和页脚。其可定制的内容如下:

itemSize属性

设定全局的Cell尺寸,如果想要单独定义某个Cell的尺寸,可以使用下面方法:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

minimumLineSpacing属性

设定全局的行间距,如果想要设定指定区内Cell的最小行距,可以使用下面方法:

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

minimumInteritemSpacing属性

设定全局的Cell间距,如果想要设定指定区内Cell的最小间距,可以使用下面方法:

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

scrollDirection属性

设定滚动方向,有UICollectionViewScrollDirectionVertical和UICollectionViewScrollDirectionHorizontal两个值。

headerReferenceSize属性与footerReferenceSize属性

设定页眉和页脚的全局尺寸,需要注意的是,根据滚动方向不同,header和footer的width和height中只有一个会起作用。如果要单独设置指定区内的页面和页脚尺寸,可以使用下面方法:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section

sectionInset属性

设定全局的区内边距,如果想要设定指定区的内边距,可以使用下面方法:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;


然后需要实现三种类型的委托:UICollectionViewDataSource, UICollectionViewDelagate和UICollectionViewDelegateFlowLayout。

@interface ViewController : UIViewController <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>

因为UICollectionViewDelegateFlowLayout实际上是UICollectionViewDelegate的一个子协议,它继承了UICollectionViewDelegate,所以只需要在声明处写上UICollectionViewDelegateFlowLayout就行了。


UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

返回collection view里区(section)的个数,如果没有实现该方法,将默认返回1:

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

返回指定区(section)包含的数据源条目数(number of items),该方法必须实现:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 7;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

返回某个indexPath对应的cell,该方法必须实现:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
if(indexPath.section==0)
{
cell.backgroundColor = [UIColor redColor];
}
else if(indexPath.section==1)
{
cell.backgroundColor = [UIColor greenColor];
}
return cell;
}

UICollectionViewCell结构上相对比较简单,由下至上:

  • 首先是cell本身作为容器view
  • 然后是一个大小自动适应整个cell的backgroundView,用作cell平时的背景
  • 再其次是selectedBackgroundView,是cell被选中时的背景
  • 最后是一个contentView,自定义内容应被加在这个view上

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath *)indexPath

为collection view添加一个补充视图(页眉或页脚)

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

设定页眉的尺寸

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section

设定页脚的尺寸

- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString*)identifier

添加页眉和页脚以前需要注册类和标识:


添加补充视图的代码示例:

[self.myCollectionView registerClass:[MyHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];
[self.myCollectionView registerClass:[MyHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwHeader"]; -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
CGSize size = {240,25};
return size;
} -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
CGSize size = {240,25};
return size;
} - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
MyHeadView *headView; if([kind isEqual:UICollectionElementKindSectionHeader])
{
headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];
[headView setLabelText:[NSString stringWithFormat:@"section %d's header",indexPath.section]];
}
else if([kind isEqual:UICollectionElementKindSectionFooter])
{
headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];
[headView setLabelText:[NSString stringWithFormat:@"section %d's footer",indexPath.section]];
}
return headView;
}

MyHeadView.h

#import <UIKit/UIKit.h>

@interface MyHeadView : UICollectionReusableView
- (void) setLabelText:(NSString *)text;
@end

MyHeadView.m

#import "MyHeadView.h"

@interface MyHeadView()

@property (strong, nonatomic) UILabel *label;

@end

@implementation MyHeadView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.label = [[UILabel alloc] init];
self.label.font = [UIFont systemFontOfSize:18];
[self addSubview:self.label];
}
return self;
} - (void) setLabelText:(NSString *)text
{
self.label.text = text;
[self.label sizeToFit];
} @end

在注册Cell和补充视图时,也可以用新建xib文件的方式:

[self.myCollectionView registerNib:[UINib nibWithNibName:@"MyCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"hxwCell"];

[self.myCollectionView registerNib:[UINib nibWithNibName:@"MySupplementaryView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];

[self.myCollectionView registerNib:[UINib nibWithNibName:@"MySupplementaryView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwFooter"];

用这种方式注册后,甚至可以不用新建类去绑定这个xib,直接通过viewWithTag的方式获取xib里的控件:

UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];

UILabel *label = (UILabel *)[view viewWithTag:1];

label.text = @"empty";

UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

设定指定Cell的尺寸

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section==0 && indexPath.row==1)
{
return CGSizeMake(50, 50);
}
else
{
return CGSizeMake(75, 30);
}
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;

设定collectionView(指定区)的边距

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
if(section==0)
{
return UIEdgeInsetsMake(35, 25, 15, 25);
}
else
{
return UIEdgeInsetsMake(15, 15, 15, 15);
}
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

设定指定区内Cell的最小行距,也可以直接设置UICollectionViewFlowLayout的minimumLineSpacing属性

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
if(section==0)
{
return 10.0;
}
else
{
return 20.0;
}
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

设定指定区内Cell的最小间距,也可以直接设置UICollectionViewFlowLayout的minimumInteritemSpacing属性

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
if(section==0)
{
return 10.0;
}
else
{
return 20.0;
}
}

UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

当指定indexPath处的item被选择时触发

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.myArray removeObjectAtIndex:indexPath.row]; [collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
}

P.s. 当你删除或添加元素时,一定要更新numberOfItemsInSection的返回情况。

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

当指定indexPath处的item被取消选择时触发,仅在允许多选时被调用

下面是三个和高亮有关的方法:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath

事件的处理顺序如下:

  1. 手指按下
  2. shouldHighlightItemAtIndexPath (如果返回YES则向下执行,否则执行到这里为止)
  3. didHighlightItemAtIndexPath (高亮)
  4. 手指松开
  5. didUnhighlightItemAtIndexPath (取消高亮)
  6. shouldSelectItemAtIndexPath (如果返回YES则向下执行,否则执行到这里为止)
  7. didSelectItemAtIndexPath (执行选择事件)

如果只是简单实现点击后cell改变显示状态,只需要在cellForItemAtIndexPath方法里返回cell时,指定cell的selectedBackgroundView:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; UIView* selectedBGView = [[UIView alloc] initWithFrame:cell.bounds];
selectedBGView.backgroundColor = [UIColor blueColor];
cell.selectedBackgroundView = selectedBGView; return cell;
}

如果要实现点击时(手指未松开)的显示状态与点击后(手指松开)的显示状态,则需要通过上面提到的方法来实现:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
} - (void)collectionView:(UICollectionView *)colView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath]; [cell setBackgroundColor:[UIColor purpleColor]];
} - (void)collectionView:(UICollectionView *)colView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath]; [cell setBackgroundColor:[UIColor yellowColor]];
}

iOS UICollectionView基础的更多相关文章

  1. IOS UICollectionView基础+UICollectionViewFlowLayout基础

    UICollectionView在众多控件中也算是比较常用的了,像淘宝在浏览宝贝时采用的就是UICollectionView,对于UICollectionView->UICollectionVi ...

  2. IOS开发基础知识碎片-导航

    1:IOS开发基础知识--碎片1 a:NSString与NSInteger的互换 b:Objective-c中集合里面不能存放基础类型,比如int string float等,只能把它们转化成对象才可 ...

  3. iOS系列 基础篇 05 视图鼻祖 - UIView

    iOS系列 基础篇 05 视图鼻祖 - UIView 目录: UIView“家族” 应用界面的构建层次 视图分类 最后 在Cocoa和Cocoa Touch框架中,“根”类时NSObject类.同样, ...

  4. iOS 面试基础题目

    转载: iOS 面试基础题目 题目来自博客:面试百度的记录,有些问题我能回答一下,不能回答的或有更好的回答我放个相关链接供参考. 1面 Objective C runtime library:Obje ...

  5. UICollectionView 基础

    在iOS开发中经常会用到UICollectionView,和UITableView同样即成UIScrollView 但是操作起来比UITableVIew要麻烦一些 ,有些地方需要注意,一下是UICol ...

  6. 一些iOS面试基础题总结

    一些iOS面试基础题总结 目录 多线程 AutoLayout objc_msgSend Runtime 消息转发 Category NSObject 与 objc_class Runloop Auto ...

  7. iOS系列 基础篇 03 探究应用生命周期

    iOS系列 基础篇 03 探究应用生命周期 目录: 1. 非运行状态 - 应用启动场景 2. 点击Home键 - 应用退出场景 3. 挂起重新运行场景 4. 内存清除 - 应用终止场景 5. 结尾 本 ...

  8. iOS系列 基础篇 04 探究视图生命周期

    iOS系列 基础篇 04 探究视图生命周期 视图是应用的一个重要的组成部份,功能的实现与其息息相关,而视图控制器控制着视图,其重要性在整个应用中不言而喻. 以视图的四种状态为基础,我们来系统了解一下视 ...

  9. iOS系列 基础篇 06 标签和按钮 (Label & Button)

    iOS系列 基础篇 06 标签和按钮 (Label & Button) 目录: 标签控件 按钮控件 小结 标签和按钮是两个常用的控件,下面咱们逐一学习. 1. 标签控件 使用Single Vi ...

随机推荐

  1. How to download a website for offline usage

    wget -U Mozilla --recursive --no-clobber --page-requisites --html-extension --convert-links -- restr ...

  2. C#.Net 如何动态加载与卸载程序集(.dll或者.exe)0-------通过应用程序域AppDomain加载和卸载程序集

    本博客中以“C#.Net 如何动态加载与卸载程序集(.dll或者.exe)”开头的都是引用莫问奴归处 微软装配车的大门似乎只为货物装载敞开大门,却将卸载工人拒之门外.车门的钥匙只有一把,若要获得还需要 ...

  3. Java之跳出多重循环

    在java里,想要跳出多重循环,有两种方法 1.在循环语句前设置一个标记,然后使用带有该标记的break语句跳出该循环 public static void main(String args[]) { ...

  4. wifi mode: AP,Client,Ad-hoc,802.11s,Pseudo Ad-hoc(ahdemo),Monitor,AP(WDS),Client(WDS)

    openwrt wifi mode:APClientAd-hoc802.11sPseudo Ad-hoc(ahdemo)MonitorAP(WDS)Client(WDS) http://forum.a ...

  5. 彻底搞懂javascript中的match, exec的区别

    在工作中经常发现一些同学把这两个方法搞混,以致把自己弄的很郁闷.所以我和大家一起来探讨一下这两个方法的奥妙之处吧. 我们分以下几点来讲解: 相同点: 1.两个方法都是查找符合条件的匹配项,并以数组形式 ...

  6. UNICODE,GBK,UTF-8区别

    简单来说,unicode,gbk和大五码就是编码的值,而utf-8,uft-16之类就是这个值的表现形式.而前面那三种编码是一兼容的,同一个汉字,那三个码值是完全不一样的.如"汉"的uncode值与g ...

  7. 结构体buf_page_t

    /** Buffer page (uncompressed or compressed) */ typedef struct buf_page_struct buf_page_t; struct bu ...

  8. LBS云端数据删除和上传

    这里采用C#模拟表单提交,实现LBS云端删除和csv格式文件的上传. 删除: /// <summary> /// 从LBS云端删除数据 /// </summary> /// & ...

  9. [转载]su认证失败

    Ubuntu 安装后,root用户默认是被锁定了的,不允许登录,也不允许 "su" 到 root.有人说这是个不好的实践,特别是对于服务器来说.我觉得对于桌面用户来说,这样安全性更 ...

  10. Obective-C之宏定义

    优(dan)美(teng)的前奏 宏定义这个东东,估计大家在代码中应该天天用吧. 在我刚刚做的一个项目中,各种往代码里码“#define”这种预处理指令. 什么动画时长啊,cell高度啊,cell的个 ...