集合视图
视图可以对多列多行的形式来展示数据,是从UITableView演变而来的,使用上和UITableView很像
1.声明一个collectionView的属性
@property(nonatomic,strong)UICollectionView * collectionView;2.创建布局对象(很重要)
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init]; layout.itemSize=CGSizeMake(80, 80); layout.minimumInteritemSpacing=10; layout.minimumLineSpacing=10; //设置四边的间隔 layout.sectionInset=UIEdgeInsetsMake(154, 30, 154, 30); layout.scrollDirection**重点内容**=UICollectionViewScrollDirectionHorizontal; //滑动方向3.初始化并添加到父视图
self.collectionView=[[UICollectionView alloc]initWithFrame:(CGRect) collectionViewLayout:layout]; //设置数据源和代理为自己 self.collectionView.delegate=self; self.collectionViewdataSource=self; [self.view addSubview:self.c]; [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:[NSBundle mainBundle]]forCellWithReuseIdentifier:@"cell"]; //必须注册一个cell否则GG4.采纳协议(3个)
<UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate>5.实现数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ //每个Section有几项 return 9; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ //每项长什么样子 CollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; return cell; }6.实现代理方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ //选中某行怎么处理 }常用方法:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ //每个cell的尺寸 return CGSizeMake(101, 169); } - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ //布局相关 return UIEdgeInsetsMake(0, 15, 0, 15); } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{ return 10; } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{ return 10; }