UICollectionView类似于UItableView实现方法也类似
1、先创建一个工程名字叫做CollectionView
2、新建另外一个名为CollectionViewCell的文件同时生成Xib文件继承自UICollectionViewCell;
3、在Xib文件中得CollectionViewCell中添加一个ImageView与一个Label;
4、将imageVi以及Label关联到UICollectionCell中,分别叫做image以及label;;
5、在Main.storyboard中删除原有的View,拖一个CollectionView进来;
6、将delegate以及dataSource关联ViewController上面 记住 不要关联到view上面;
7、选中CollectionViewCell的属性中得Class修改为 CollectionViewCell;
7、选中CollectionView的属性,可以修改其属性,比如是垂直滑动,还是水平滑动,选择Vertical或Horizontal;
8、在CollectionViewCell.m里面初始化CollectionCell.xib文件;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionViewCell" owner:self options:nil];
// 如果路径不存在,return nil
if (arrayOfViews.count < 1)
{
return nil;
}
// 如果xib中view不属于UICollectionViewCell类,return nil
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]])
{
return nil;
}
// 加载nib
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
9、在ViewController.h里面声明UICollectionViewDelegate,UICollectionViewDataSource;
10、在ViewDidLoad方法中注册CollectionViewCell的类,在ViewDidLoad方法中添加,不注册,将无法加载,程序崩溃其中,CollectionCell是这个Cell的标识;
[self.CollectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"CollectionCell"];
11、在ViewController.m里面创建Cell 并且可以给Cell的属性image以及label添加数据
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *Cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
Cell.image.image = [UIImage imageNamed:@"appIcon57.png"];
Cell.label.text = @"ddd";
Cell.label.textColor = [UIColor blueColor];
Cell.backgroundColor = [UIColor redColor];
return Cell;
}
12控制每个section的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 150;
}
113控制section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 2;
}
14、控制UICollectionVieCell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(96, 100);
}
15、返回这个UICollectionViewUCell能否被返回
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
总结:
关于CollectionView的创建和tabeleVIew差不多,只要注意一些细节比如关联代码的时候一定要关联争取的NIB;Cell一定要初始化注册不然程序会崩溃;
利用XIb文件时要注意修改identifier以及Class;
Xib文件一定要初始化;