強(qiáng)大之處
- 支持水平和垂直兩種方向的布局
- 通過layout配置方式進(jìn)行布局
- 類似于TableView中的cell特性外,CollectionView中的Item大小和位置可以自由定義
- 通過layout布局回調(diào)的代理方法,可以動態(tài)的定制每個item的大小和collection的布局屬性
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建一個layout布局類
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
//設(shè)置布局方向為垂直流布局
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//設(shè)置每個item的大小為100*100
layout.itemSize = CGSizeMake(100, 100);
//創(chuàng)建collectionView 通過一個布局策略layout來創(chuàng)建
UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
//代理設(shè)置
collect.delegate=self;
collect.dataSource=self;
//注冊item類型 這里使用系統(tǒng)的類型(collectionView在完成代理回調(diào)前,必須注冊一個cell)
[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
[self.view addSubview:collect];
}
//返回分區(qū)個數(shù)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//返回每個分區(qū)的item個數(shù)
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
//返回每個item
-(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;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。