本章通过先总体介绍UICollectionView及其常用方法,再结合一个实例,了解如何使用UICollectionView。
UICollectionView 和 UICollectionViewController 类是iOS6 新引进的API,用于展示集合视图,布局更加灵活,可实现多列布局,用法类似于UITableView 和 UITableViewController 类。
使用UICollectionView 必须实现UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout这三个协议。
下面先给出常用到的一些方法。(只给出常用的,其他的可以查看相关API)
- #pragma mark -- UICollectionViewDataSource
-
- -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- {
- return 30;
- }
-
- -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
- {
- return 1;
- }
-
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString * CellIdentifier = @"GradientCell";
- UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
-
- cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];
- return cell;
- }
- #pragma mark --UICollectionViewDelegateFlowLayout
-
- - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return CGSizeMake(96, 100);
- }
-
- -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
- {
- return UIEdgeInsetsMake(5, 5, 5, 5);
- }
- #pragma mark --UICollectionViewDelegate
-
- -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
- cell.backgroundColor = [UIColor whiteColor];
- }
-
- -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return YES;
- }
layout.minimumInteritemSpacing = 0;//每列最小边距
layout.minimumLineSpacing = 0;//每行最小边距
下面通过一个例子具体介绍下。(例子来自网络。但是是通过第三方获得的,无法取得链接。还望见谅。)
iOS CollectionView的出现是一大福利,再也不用用TableView来定义复杂的多栏表格了,用法与Table类似,只是Cell必须自己添加,无默认模式
由于CollectionView没有默认的Cell布局,所以一般还是自定义方便又快捷
一、自定义Cell
1、新建类CollectionCell继承自UICollectionViewCell
2、新建Xib,命名为CollectionCell.xib
a.选中CollectionCell.xib删掉默认的View,从控件中拖一个Collection View Cell(图3)到画布中,设置大小为95*116;
b.选中刚刚添加的Cell,更改类名为CollectionCell,如图4
c.在CollectionCell.xib的CollectionCell中添加一个ImageView和一个Label(图5)
d.创建映射, 图6,图7
e.选中CollectionCell.m , 重写init方法
- - (id)initWithFrame:(CGRect)frame
- {
- self = [super initWithFrame:frame];
- if (self)
- {
-
- NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options:nil];
-
-
- if (arrayOfViews.count < 1)
- {
- return nil;
- }
-
- if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]])
- {
- return nil;
- }
-
- self = [arrayOfViews objectAtIndex:0];
- }
- return self;
- }
f.选中CollectionCell.xib 修改其identifier为CollectionCell。
二、定义UICollectionView;
1、拖动一个Collection View到指定ViewController的View上
2、连线dataSource和delegate,并创建映射,命名为CollectionView
3、选中CollectionView的标尺,将Cell Size的Width和Height改成与自定义的Cell一样的95*116,图8
4、选中CollectionView的属性,可以修改其属性,比如是垂直滑动,还是水平滑动,选择Vertical或Horizontal
5、选中CollectionViewCell,修改Class,继承自CollectionCell
5、在ViewDidLoad方法中声明Cell的类,在ViewDidLoad方法中添加,此句不声明,将无法加载,程序崩溃
其中,CollectionCell是这个Cell的标识(之前几步已经定义过了。 )
- [self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
6、在ViewController.h中声明代理
- @interface ViewController : UIViewController
7、在.m文件中实现代理方法
-
- -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- {
- return 12;
- }
-
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
-
- CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
-
-
- NSString *imageToLoad = [NSString stringWithFormat:@"%d.png", indexPath.row];
-
- cell.imageView.image = [UIImage imageNamed:imageToLoad];
-
- cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.row,(long)indexPath.section];
-
- return cell;
- }
8 。效果如图10
点击某项后跳转事件与UITableView类似,实现代理方法
- -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
即可,不赘述
代码创建
swift
let flowLayout =UICollectionViewFlowLayout()
flowLayout.itemSize =CGSizeMake(UIScreen.mainScreen().bounds.size.width,100)
flowLayout.scrollDirection =UICollectionViewScrollDirection.Vertical//设置垂直显示
flowLayout.sectionInset =UIEdgeInsetsMake(0,1,0,1)//设置边距
flowLayout.minimumLineSpacing =0.0;//每个相邻layout的上下
flowLayout.minimumInteritemSpacing =0.0;//每个相邻layout的左右
flowLayout.headerReferenceSize =CGSizeMake(0,0);
self.siteCollect =UICollectionView(frame:CGRectMake(0,270,100,100), collectionViewLayout: flowLayout)
self.siteCollect!.setTranslatesAutoresizingMaskIntoConstraints(false)
self.siteCollect!.backgroundColor =UIColor.whiteColor()
self.siteCollect!.alwaysBounceVertical =true
self.siteCollect!.delegate =self
self.siteCollect!.dataSource =self
self.view.addSubview(self.siteCollect!)
self.siteCollect!.registerClass(SiteDetailCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
Object-C
-(
void
) initCollectionView{
UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize=CGSizeMake(100,100);
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
_gridView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, 410)];
_gridView.dataSource=
self
;
_gridView.delegate=
self
;
[_gridView setBackgroundColor:[UIColor blueColor]];
[_gridView setCollectionViewLayout:flowLayout];
[_gridView registerClass:[UICollectionViewCell
class
] forCellWithReuseIdentifier:@
"CollectionViewIdentifier"
];
[
self
.view addSubview:_gridView];
}
初始化:
//初始化布局类(UICollectionViewLayout的子类)
UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
//初始化collectionView
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
//设置代理
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
--------------------
需要实现的协议:
UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
PS:UICollectionViewDelegateFlowLayout是UICollectionViewDelegate的子协议
--------------------
注册相应的UICollectionViewCell子类到collectionView用来从队列提取和显示
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
PS:如果是用nib创建的话,使用下面这个函数来注册。
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
如果需要显示每个section的headerView或footerView,则还需注册相应的UICollectionReusableView的子类到collectionView
elementKind是header或footer的标识符,只有两种可以设置UICollectionElementKindSectionHeader和UICollectionElementKindSectionFooter
- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
PS:如果是用nib创建的话,使用下面这个函数来注册。
- (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;
--------------------
实现协议的函数:
跟UITableView的DataSource和Delegate很像,大可自行代入理解。
DataSource:
//每一组有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
//定义并返回每个cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
//collectionView里有多少个组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
//定义并返回每个headerView或footerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
上面这个方法使用时必须要注意的一点是,如果布局没有为headerView或footerView设置size的话(默认size为CGSizeZero),则该方法不会被调用。所以如果需要显示header或footer,需要手动设置size。
可以通过设置UICollectionViewFlowLayout的headerReferenceSize和footerReferenceSize属性来全局控制size。或者通过重载以下代理方法来分别设置
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
Delegate:
//每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
//设置每组的cell的边界, 具体看下图
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
//cell的最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
//cell的最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
//cell被选择时被调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
//cell反选时被调用(多选时才生效)
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
本文出自 “rainbownight” 博客,请务必保留此出处http://rainbownight.blog.51cto.com/1336585/1323780