collectionView的运用

现在开始上班了,很久没有更新了.今天写个collectionView给大家看看,这种样式的collectionview在很多app里面都有运用,希望能够帮助到大家.
先看看效果图吧



废话不多说,给打击看看代码吧.
首先肯定需要自定义一个CollectionViewCell.

@interface MyCollectionViewCell : UICollectionViewCell
typedef enum : NSInteger
{
    cellStyleDefault = 0,
    cellStyleSelected = 1,
    cellStyleAdd = 2,
}CollectionViewCellStyle;

@property(nonatomic, assign)CollectionViewCellStyle cellStyle;
@property(nonatomic, strong)UILabel *label;
@property(nonatomic, strong)UIImageView *imageView;
@property(nonatomic, strong)NSArray *array;
@property(nonatomic, strong)NSMutableArray *dataArray;
-(void)layoutSubviews;
@end

这里用一个枚举来表示不同类型的cell.通过判断点击来决定具体运用哪种cell.

#import "MyCollectionViewCell.h"

@implementation MyCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _label = [[UILabel alloc]init];
        _imageView = [[UIImageView alloc]init];
        
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    [_label setFrame:self.bounds];
    _label.textAlignment = 1;
    _label.font = [UIFont systemFontOfSize:15];
    _imageView.frame = self.bounds;
    switch (_cellStyle) {
        case cellStyleDefault:
            self.layer.borderColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1].CGColor;
            self.layer.masksToBounds = YES;
            self.layer.borderWidth = 1.8;
            self.layer.cornerRadius = 20;
            self.label.textColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1];
            self.backgroundColor = [UIColor whiteColor];
            [self.contentView addSubview:_label];
            break;
        case cellStyleSelected:
            self.layer.borderColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1].CGColor;
            self.layer.masksToBounds = YES;
            self.layer.borderWidth = 1.8;
            self.layer.cornerRadius = 20;
            self.label.textColor = [UIColor whiteColor];
            self.backgroundColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1];
            [self.contentView addSubview:_label];
            break;
        case cellStyleAdd:
            [self.imageView setImage:[UIImage imageNamed:@"屏幕快照 2016-02-22 下午7.29.08.png"]];
            self.backgroundColor = [UIColor whiteColor];
            [self.contentView addSubview:_imageView];
            break;
        default:
            break;
    }   
}
@end

再定义一个collection的头视图.

@interface SectionHeaderViewCollectionReusableView : UICollectionReusableView
@property(nonatomic, strong)UILabel *titleLabel;
@end
#import "SectionHeaderViewCollectionReusableView.h"

@implementation SectionHeaderViewCollectionReusableView
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createViews];
    }
    return self;
}

-(void)createViews
{
    _titleLabel = [[UILabel alloc]init];
    [self addSubview:_titleLabel];
    
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    _titleLabel.frame = CGRectMake(20, 30, 375, 50);
    _titleLabel.font = [UIFont systemFontOfSize:20];
    

}

@end

剩下的就是在Viewcontroller里面了,代码不难,看看就能懂.

#import "ViewController.h"
#import "MyCollectionViewCell.h"
#import "SectionHeaderViewCollectionReusableView.h"
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong)NSMutableArray *ownHobby;//自定义的兴趣
@property(nonatomic, strong)UICollectionView *collection;
@property(nonatomic, strong)NSMutableArray *dataArr;//公共兴趣

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = 7 ;
    flowLayout.minimumLineSpacing = 20 ;
    flowLayout.sectionInset = UIEdgeInsetsMake(0 , 5 , 0 , 10 );
    flowLayout.itemSize = CGSizeMake(75 , 30 );
    _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 400) collectionViewLayout:flowLayout];
    [_collection registerClass:[SectionHeaderViewCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    _collection.bounces = NO;
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [_collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [self.view addSubview:_collection];
        _dataArr = @[@{
                         @"type":@(0),
                         @"text":@"篮球"},
                     @{@"type":@(0),
                       @"text":@"足球"},
                     @{@"type":@(0),
                       @"text":@"冲浪爱好者"},
                     @{@"type":@(0),
                       @"text":@"游戏王"},
                     @{@"type":@(0),
                       @"text":@"学习机器"},
                     @{@"type":@(0),
                       @"text":@"跆拳道",
},
                     @{@"type":@(0),
                       @"text":@"英雄联盟"
                       }
                     ].mutableCopy;
    _ownHobby = [NSMutableArray array];
}

-(void)textfiledShow
{
    if (_ownHobby.count  == 3) {
        UIAlertController *alert1 = [UIAlertController alertControllerWithTitle:@"超过个数限制" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert1 addAction:action];
        [self presentViewController:alert1 animated:YES completion:nil];
    }
    else
    {
    UIAlertController *alert1 = [UIAlertController alertControllerWithTitle:@"请输入您的爱好" message:@"5个字以内" preferredStyle:UIAlertControllerStyleAlert];
    [alert1 addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.keyboardType = 3;
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"%@",[alert1.textFields objectAtIndex:0].text);
        [_ownHobby addObject:[alert1.textFields objectAtIndex:0].text];
        [_collection reloadSections:[ NSIndexSet indexSetWithIndex:1]];
    }];
    [alert1 addAction:action];
    [alert1 addAction:action1];
    [self presentViewController:alert1 animated:YES completion:nil];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return _dataArr.count;
    }else
    {
        return _ownHobby.count + 1;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSDictionary *item = [NSDictionary dictionaryWithDictionary:_dataArr[indexPath.row]];
        int type = [NSString stringWithFormat:@"%@",item[@"type"]].intValue;
        NSString *title = item[@"text"];
        MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
        cell.label.text = title;
        cell.cellStyle = type;
        [cell.imageView removeFromSuperview];
        [cell layoutSubviews];
        return cell;
    }
   else
   {
       if (_ownHobby.count == indexPath.row) {
           MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
           UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textfiledShow)];
           [cell.imageView addGestureRecognizer:tap];
           cell.imageView.userInteractionEnabled = YES;
           cell.cellStyle = cellStyleAdd;
           cell.layer.masksToBounds = NO;
           cell.layer.borderWidth = 0;
           cell.layer.cornerRadius = 0;
           [cell layoutSubviews];

           return cell;
       }
      else
      {
          MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
          cell.label.text = _ownHobby[indexPath.row];
          cell.cellStyle = 1;
          [cell layoutSubviews];
          [cell.imageView removeFromSuperview];
          return cell;
      }
   }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  2;
}
#pragma mark 头视图size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
        CGSize size = {self.view.frame.size.width, 80.0};
        return size;
}
#pragma mark 每个Item大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
        return CGSizeMake([self lengthWithString:item[@"text"]] * 28, 40);
    }
    else
    {
        if (indexPath.row == _ownHobby.count) {
            return CGSizeMake(70, 50);
        }
        else
        {
            return CGSizeMake([self lengthWithString:[_ownHobby objectAtIndex:indexPath.row]] * 28, 40);
        }
    }
}
-(CGFloat)lengthWithString:(NSString *)string
{
    return [string length];
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            SectionHeaderViewCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
            headView.titleLabel.text = @"选择你的兴趣特长,最多3个";
            return headView;
        }
       else
       {
           SectionHeaderViewCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
           headView.titleLabel.text = @"添加自定义标签最多3个";
           return headView;
       }
    }
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSLog(@"%ld",indexPath.row);
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_dataArr[indexPath.row]];
        NSInteger time = 0;
        for (NSDictionary *dic in _dataArr) {
            if ([[dic objectForKey:@"type"]intValue] == 1) {
                time++;
            }
        }
        if (time == 3) {
            if ([[dic objectForKey:@"type"]intValue] == 1)
            {
                [dic setValue:@(0) forKey:@"type"];
                _dataArr[indexPath.row] = dic;
                [_collection reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
        else
        {
            if ([[dic objectForKey:@"type"]intValue] == 0) {
                [dic setValue:@(1) forKey:@"type"];
                _dataArr[indexPath.row] = dic;
                 [_collection reloadItemsAtIndexPaths:@[indexPath]];
            }
            else
            {
                [dic setValue:@(0) forKey:@"type"];
                _dataArr[indexPath.row] = dic;
                 [_collection reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
    }
    else
    {
        if (_ownHobby.count) {
            [_ownHobby removeObjectAtIndex:indexPath.row];
            [_collection reloadSections:[NSIndexSet indexSetWithIndex:1]];
        }
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

运行一下试试吧.
好了,今天就到这里,以后工作遇到什么有用的东西我就抽空写下了,希望能帮助到大家.谢谢大家😄

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,010评论 4 62
  • Github地址:-CollectionViewLayout-CollectionViewFlowLayout- ...
    大冲哥阅读 5,168评论 1 10
  • 观自在,在我这个年龄我能想到两种不同的看法。 观了,万事万物自然在,不观,或许在或许不在,这里强调...
    子夜月阅读 736评论 3 3
  • 黎明就要别离 你的眼睛 慌乱地掠过我 期盼的眸 我看到 你坚硬的睫毛划过 没有再见 只有想念 黎明虽在黑夜之后 我...
    天苍草芜阅读 153评论 0 1
  • 小朋友们的世界就是美好又单纯哈,看着小朋友看那些鱼儿和小猴子们的表情和眼神,我觉得我也干净纯粹了。小孩子们肯定看不...
    啾啾fing阅读 234评论 0 0