//生成流布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
//设置滚动方向
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//生成view视图,类似于Tabview
UICollectionView *colletionview = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
[self addSubview:colletionview];
//由于前面使用CGRectZero,我使用Masonry进行布局
[colletionview mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(LWLWindowsW-10);
make.height.mas_equalTo(LWLWindowsW+20);
make.centerX.mas_equalTo(self.mas_centerX);
make.top.mas_equalTo(30);
}];
//遵守两个代理协议
colletionview.delegate = self;
colletionview.dataSource = self;
colletionview.backgroundColor = [UIColor whiteColor];
//注册单元格,只能通过注册的方式,不可以生成的
[colletionview registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
协议的方法,这点和tabview一样
//section个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 9;
}
//每个单元格
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
return cell;
}
//选中时候的操作
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}