iOS 自定义collectionview实现九宫格布局

最想项目里要实现九宫格布局图标的需要,在网上看了看有比较多酷炫布局效果,介于项目要求实现的是比较简洁的效果,加上自己还是比较菜需要苦练技术[尴尬],最近闲了下来,就整理了一个小demo,其中collectionview和collectionviewcell由于使用的地方比较多,我粗鄙的自定义了一下,写的不是很好,欢迎大神们指正哦~~~话不多说,先上效果图


iOS 自定义collectionview实现九宫格布局_第1张图片
56878E84-371C-4D16-9BD7-0B204559A09F.png

1.首先看自定义ZXNineCollectionView的代码,这里不需要讲太多,直接继承自collectionview,实现代理UICollectionViewDelegate,UICollectionViewDataSource方法,设置好需要展示的样式;首先看ZXNineCollectionView.h文件

#import 

@class ZXNineCollectionView;
@protocol ZXNineCollectionViewDelegate 
- (void)menuCollectionView:(ZXNineCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath dataDic:(NSDictionary*)dataDic;
@end

@interface ZXNineCollectionView : UICollectionView
//自定义外界方法
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout DataArray:(NSArray *)dataArray cellId:(NSString *)cellId headerId:(NSString *)headerId;
//代理
@property(nonatomic,weak)idnineDelegate;

@end

2.再看ZXNineCollectionView.m文件:

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout DataArray:(NSArray *)dataArray cellId:(NSString *)cellId headerId:(NSString *)headerId{
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self){
        //设置代理
        self.delegate = self;
        self.dataSource = self;
        self.backgroundColor = [UIColor clearColor];
        self.dataArr = dataArray;
        self.cellId = cellId;
        self.headerId = headerId;
        
    }
    return self;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  
    return _dataArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataArr[section] count];
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZXNineCollectionViewCell *cell = (ZXNineCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:_cellId forIndexPath:indexPath];
    cell.name = _dataArr[indexPath.section][indexPath.row];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:_headerId forIndexPath:indexPath];
        header.backgroundColor = [UIColor whiteColor];
        NSString * name = [NSString stringWithFormat:@"标题%ld",(long)indexPath.section];
        UIView * view = [self addHeaderViewWithTitle:name andFrame:header.bounds];
        for (UIView *view in header.subviews) {
            [view removeFromSuperview];
        } // 防止复用分区头
        [header addSubview:view];
        return header;
    } else {
        return nil;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.nineDelegate respondsToSelector:@selector(menuCollectionView:didSelectItemAtIndexPath:dataDic:)]){
        //实际应用时可以传递点击item对应的data
        [self.nineDelegate menuCollectionView:self didSelectItemAtIndexPath:indexPath dataDic:nil];
    }
    
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(screenWidth/3, screenWidth * 2/9);
}


//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if ([_headerId isEqualToString:@"headerId"]) {
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(screenWidth, screenHeight * 50/667);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

3.自定义collectionviewcell,这里碰到过一些坑,一开始我以为跟自定义tableViewcell一样,但发现不行,在网上找了找实现了,贴上代码:

@interface ZXNineCollectionViewCell (){
    UIImageView * imageView;
    UILabel * label;
}

@end

@implementation ZXNineCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self createZXNineCollectionViewCellUIWihFrame:frame];
    }
    
    return self;
}

- (void)createZXNineCollectionViewCellUIWihFrame:(CGRect)frame{
    CGFloat height = KscreenWidth * 2/3;
    imageView = [[UIImageView alloc] init];
    
    imageView  = [[UIImageView alloc] initWithFrame:CGRectMake(height/4, height/8, height/2, height/2)];
    imageView.image = [UIImage imageNamed:@"icon_homepage_hotelCategory"];
    [self.contentView addSubview:imageView];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(0, height * 17/24, height, height/6)];
    label.textAlignment = NSTextAlignmentCenter;
//    label.backgroundColor = [UIColor redColor];
    label.font = [UIFont systemFontOfSize:15];
    [self.contentView addSubview:label];
    
   
    
}

- (void)setName:(NSString *)name{
    _name = name;
    label.text = name;
}

4.这里的cell在刚才前面说的collectionview里面调用起来比较简便:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZXNineCollectionViewCell *cell = (ZXNineCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:_cellId forIndexPath:indexPath];
    cell.name = _dataArr[indexPath.section][indexPath.row];
    return cell;
}

5.最后在控制器调用的时候直接懒加载上面自定义的collectionview就行,注意设置好layout~

@property (nonatomic, strong) ZXNineCollectionView *nineCollectionView;

@end

@implementation ViewController


- (ZXNineCollectionView *)nineCollectionView{
    if (!_nineCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        NSString * cellId = @"CellId";
        NSString * headerId = @"HeaderId";
        _nineCollectionView = [[ZXNineCollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout DataArray:self.dataArr cellId:cellId headerId:headerId];
        _nineCollectionView.backgroundColor = [UIColor clearColor];
        _nineCollectionView.nineDelegate = self;
        [_nineCollectionView registerClass:[ZXNineCollectionViewCell class] forCellWithReuseIdentifier:cellId];
        _nineCollectionView.showsVerticalScrollIndicator = YES;
        [_nineCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    }
    return _nineCollectionView;
}

demo地址ZXCollectionviewDemo

你可能感兴趣的:(iOS 自定义collectionview实现九宫格布局)