UICollectionView是一种类似于表格一样的视图,它有4个主要部分:
1、单元格:它是UICollectionView中的一个个单元格
2、节:它是UICollectionView中的一行数据,可以由一个或者多个单元格组成
3、补充视图:它是节的头部视图和尾部视图
4、装饰视图:UICollectionView的背景视图
UICollectionView继承于UIScrollView(滚动视图)。它也有两个协议——UICollectionViewDelegate和UICollectionViewDatasource。UICollectionViewCell是它的单元格类,它的布局是由UICollectionViewLayout类定义的,它是一个抽象类。UICollectionViewFlowLayout类是UICollectionViewLayout的子类。对于复杂的布局,可以自定义UICollectionViewLayout类。UICollectionView对应的控制器是UICollectionViewController类。
下面这个Demo实现了一个4行2列的UICollectionView,点击其中一个打印一条信息。
界面如下:
因为子类化,所以将单元格视图单独建立了一个类
ViewController.m代码如下:
#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
NSArray *_events; //定义接收图片数组
int columnNumber; //定义一行几个单元格
}
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"events.plist" ofType:nil];
_events = [[NSArray alloc]initWithContentsOfFile:filePath];
columnNumber = 2;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
}
#pragma mark - UICollectionView数据源协议方法
//可选实现
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//返回行数
int num = _events.count % columnNumber;
if (num == 0) {//表明除尽
return _events.count / columnNumber;
} else {//表明未除尽,返回的时候要多一行
return _events.count / columnNumber + 1;
}
}
//必须实现
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//返回某行中的单元格数量
return columnNumber;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//为单元格提供数据
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
NSDictionary *event = _events[indexPath.section * columnNumber +indexPath.row];
cell.label.text = [event objectForKey:@"name"];
cell.imageView.image = [UIImage imageNamed:event[@"image"]];
return cell;
}
#pragma mark - UICollectionView代理协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *event = _events[indexPath.section * columnNumber +indexPath.row];
NSLog(@"选中了:%@",event[@"name"]);
}
@end
CollectionViewCell.h代码如下:
#import <UIKit/UIKit.h>
@interface CollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
为了进一步体现子类化也可以将给单元格赋值数据的代码转移到CollectionViewCell.m的代码中去实现。实现过程:在CollectionViewCell.h文件中声明一个字典对象用于在ViewController中去接收数据然后在CollectionViewCell.m中通过重构initWithFrame方法来将数据展现出来,由于这里面的视图和数据比较简单,所以放在ViewController中展现了数据。