UICollectionView和UITableView有很多类似之处,可以先温习一下tableView。UICollectionView继承UIScrollView,有两个代理方法和一个UICollectionViewDelegateFlowLayout,我们目前先了解UICollectionView的基础用法。
1.初始化的时候必须有UICollectionViewFlowLayout对象,如果没有UICollectionViewFlowLayout对象,UICollectionView是无法显示出来的。
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
2.如果要设置一个headerView(头视图),先要设置HeaderReferenceSize即头视图的frame,然后注册头视图。
//设置flowLayout的头视图frame
[flowLayout setHeaderReferenceSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.width*3/4)];
//注册头视图以便复用头视图[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"self.navView"];
3.注册cell。一般我们自己要写一个UICollectionCell来自定义cell的显示。
[self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
-(void)initCollectionView{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, screenW, screenH-64)collectionViewLayout:flowLayout];
self.collectionView.backgroundColor = [UIColor whiteColor];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
[self.view addSubview:self.collectionView];
}
//返回UICollectionView有几个section
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//每个section有几个Item
-(NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return cellCityArray.count;
}
//返回UICollectionViewCell的代理方法,处理复用cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"cell";
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
[cell sizeToFit];
cell.imgView.image = [UIImage imageNamed:cellImageArray[indexPath.item]];
cell.cityText.text = cellCityArray[indexPath.item];
return cell;
}
//调节每个item的大小size代理方法
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(collectionWidth, 3*collectionWidth/5);
}
//调节每个item的edgeInsets代理方法
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(10, 20, 10, 20);
}
//点击每个item事件的代理方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSString *string = cellCityArray[indexPath.item];
self.selectString(string);
[self dismissViewControllerAnimated:YES completion:nil];
}