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

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


56878E84-371C-4D16-9BD7-0B204559A09F.png

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

#import <UIKit/UIKit.h>

@class ZXNineCollectionView;
@protocol ZXNineCollectionViewDelegate <NSObject>
- (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)id<ZXNineCollectionViewDelegate>nineDelegate;

@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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容