众所周知,UICollectionView是ios6才最新引进来的API,用于展示集合视图,可实现多列布局;
经常听人说起 UICollectionView怎么好用,由于之前在赶项目也没有什么时间去学习这个,现在闲下来,学习了简单的使用,感觉功能还是蛮强大的,相对UIScrollView和UITableView它相对而言更灵活了;
UICollectionView有两种方式,一种是 Xib还有一种是纯代码,今天暂时是学习的Xib的方式 ;
学习总结如下:
1.创建工程,要实现UICollectionView需要ViewController实现它的三个代理协议UICollectionViewDataSource、UICollectionViewDelegate、UICollectionViewDelegateFlowLayout;
2.声明相关的UICollectionView的类如下:
@property (nonatomic,strong)UICollectionView *collectionView;
3.创建Xib文件,命名为CollectionCell,在xib中拖入如下视图
拖入后如下图所示,
在这个cell里面添加相应的控件,添加完如下所示:
到这里xib文件算是创建完了;
4.在ViewController.m文件中初始化 UICollectionView如下所示:
<span style="font-size:14px;"> UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
self.collectionView.delegate = self; //实现代理
self.collectionView.dataSource = self; //实现数据源方法
self.collectionView.allowsMultipleSelection = YES; //实现多选,默认是NO
[self.view addSubview:self.collectionView];</span>
5.在ViewDidLoad中通过Nib生成cell,然后注册 Nib的view需要继承 UICollectionViewCell
[self.collectionViewregisterNib:[UINibnibWithNibName:@"CollectionCell"bundle:nil]forCellWithReuseIdentifier:@"collectionCellID"];
6.实现他的代理方法,主要有如下几个
//有多少个item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCellID" forIndexPath:indexPath];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1]; //在创建Xib的时候给了控件相应的tag值
UILabel *label = (UILabel *)[cell viewWithTag:2];
[imageView setImage:[UIImage imageNamed:[self.dataArray objectAtIndex:indexPath.row]]];
[label setText:[self.dataArray objectAtIndex:indexPath.row]];
cell.backgroundColor = [UIColor redColor];
return cell;
}
//UICollectionViewCell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(90, 116);
}
//选择cell时
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
}
//取消cell时
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
}
完成以上操作运行 效果图如下;