代码创建九宫格
1、为了以后创建九宫格的时候不再到处找以前的项目,方便查看复制,直接在这写一篇。
基本设置
//创建一个布局类对象 UICollectionViewFlowLayout *flowl=[[UICollectionViewFlowLayout alloc]init]; flowl.itemSize=CGSizeMake((IPONE_W -30)/4, (IPONE_W -30)/4); //设置格子内容与边上左xia右距离 flowl.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0); flowl.minimumLineSpacing = 10;//格子行间距 flowl.minimumInteritemSpacing = 10; //格子竖间距 //设置格子滚动方向 flowl.scrollDirection = UICollectionViewScrollDirectionHorizontal; CGRect rect=CGRectMake(0, 0, IPONE_W, IPONE_H); mmcollecV =[[UICollectionView alloc]initWithFrame:rect collectionViewLayout:flowl];
单元格和头尾视图一般自定义
//注册单元格 [mmcollecV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"mycell"]; //设置头尾视图大小 //预留空间 [flowl setHeaderReferenceSize:CGSizeMake(mmcollecV.frame.size.width, 50)]; [flowl setFooterReferenceSize:CGSizeMake(mmcollecV.frame.size.width, 50)]; //注册头部视图 [mmcollecV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myhead"]; //注册尾部视图 [mmcollecV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myfoot"]; //添加代理 mmcollecV.dataSource=self; mmcollecV.delegate=self; [self.view addSubview:mmcollecV];
代理实现
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 10; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mycell" forIndexPath:indexPath]; cell.backgroundColor = [UIColor redColor]; return cell; } //设置头尾部内容 -(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView *reusb=nil; if (kind ==UICollectionElementKindSectionHeader) { //定制头部内容 UICollectionReusableView *head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"muyhead" forIndexPath:indexPath]; reusb=head; } if (kind==UICollectionElementKindSectionFooter) { UICollectionReusableView *foot = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myfoot" forIndexPath:indexPath]; reusb =foot; } return reusb; }