之前写了一个Xib创建UiCollectionView的简单使用的demo,现在写个用纯代码写的,原理其实差不多,只是那个Cell之前是用XIb现在用一个继承UiColelctionViewCell的类代替,如下所示:
1.首先创建一个CollectionCell的类继承UIColelctionViewCell
@interface CollectionCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *label;
@end
里面的UIImageView和UILabel控件是我定义的加在cell上面的控件;
2.在OneViewController的.h文件中实现三个协议:如下所示,并声明UICollectionView控件
<span style="font-size:14px;">@interface OneViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@end</span>
3.在OneViewController的.m文件中初始化UICollectionView控件
<span style="font-size:14px;"> UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; //水平滚动
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 100) collectionViewLayout:flowLayout];
self.collectionView.delegate = self; //实现代理
self.collectionView.dataSource = self; //实现数据源方法
self.collectionView.showsHorizontalScrollIndicator = NO;
[self.view addSubview:self.collectionView];
//注册cell,通过创建的CollectionCell
[self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CELL"];</span>
<span style="font-size:14px;">#pragma mark UICollectionViewDelegateFlowLayout的代理方法
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100, 100);
}
#pragma mark UICollectionViewDataSource的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
[cell.imageView setImage:[UIImage imageNamed:[self.dataArray objectAtIndex:indexPath.row]]];
[cell.label setText:[self.dataArray objectAtIndex:indexPath.row]];
cell.backgroundColor = [UIColor redColor];
return cell;
}
#pragma mark UICollectionViewDelegate的代理方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionCell *cell = (CollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionCell *cell = (CollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
}</span>
5.ok了运行完效果图如下:
可以左右滑动的;