代碼建立九宮格

     一、爲了之後建立九宮格的時候再也不處處找之前的項目,方便查看複製,直接在這寫一篇。佈局

 

基本設置spa

   //建立一個佈局類對象
    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];

 

代理實現code

- (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;
}
相關文章
相關標籤/搜索