代码创建UICollectionView(带分组header)

1,在viewController中实现collectionView的三个协议

<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

2,创建cell

//.h
#import <UIKit/UIKit.h>
#import "ListModel.h"
@interface AppListCollectCell : UICollectionViewCell
@property (nonatomic,strong) ListModel *listModel;
@property (nonatomic,strong) UIImageView *imageV;
@property (nonatomic,strong) UILabel *lab;
@end
//.m
#import "AppListCollectCell.h"

@implementation AppListCollectCell

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self=[super initWithFrame: frame]) {
        _imageV=[[UIImageView alloc] init];
_imageV.contentMode=UIViewContentModeScaleAspectFill;
        _imageV.layer.cornerRadius=22.5;
        _imageV.clipsToBounds=YES;
        [self addSubview:_imageV];

        _lab = [[UILabel alloc] init];
        _lab.font = H_FONT12;
        if (ScreenWidth == 320) {
            _lab.font = H_FONT11;
        }
        _lab.textColor = H_BLACKTEXTCOLOR;
        _lab.textAlignment=NSTextAlignmentCenter;
        [self addSubview:_lab];

        [_imageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo (self.mas_top).mas_offset(0);
            make.width.mas_equalTo(45);
            make.height.mas_equalTo(45);
        }];

        [_lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo (_imageV.mas_bottom).mas_offset(12);
            make.left.equalTo (self.mas_left).mas_offset(-18);
            make.right.equalTo (self.mas_right).mas_offset(18);
            make.height.mas_equalTo(14);
        }];
    }
    return self;
}

- (void)setListModel:(AppListModel *)listModel
{
    [_imageV sd_setImageWithURL:[NSURL URLWithString:listModel.avatar] placeholderImage:[UIImage imageNamed:H_HOMEPLACE]];
    _listModel = listModel;
    _lab.text = listModel.name;
}

3,创建headerView

//.h
#import <UIKit/UIKit.h>

@interface HomeCollectionHeader : UICollectionReusableView

@property (nonatomic,strong) UILabel *headeLab;

@end
#import "HomeCollectionHeader.h"

@implementation HomeCollectionHeader

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {

        [self createSubViews];
    }
    return self;
}

- (void)createSubViews
{
    UIView *lineView = [UIView new];
    lineView.backgroundColor = H_LINECOLOR;
    lineView.frame = CGRectMake(0, 0, ScreenWidth, 0.5);
    [self addSubview:lineView];

    self.headeLab = [UILabel new];
    self.headeLab.frame = CGRectMake(20, 25, 300, 14);
    self.headeLab.font = H_FONTCONTENTNAME;
    self.headeLab.textColor = H_GRAYTEXTCOLOR;
    [self addSubview:self.headeLab];
}
@end

4,viewController

这里写代码片
#import "CollectionViewController.h"
#import "HomeCollectionHeader.h"
#import "AppListCollectCell.h"

@interface CollectionViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *mainCollectionView;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置collectionView滚动方向
//    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 40);
    //该方法也可以设置itemSize
    layout.itemSize =CGSizeMake(110, 150);

    //2.初始化collectionView
    mainCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:mainCollectionView];
    mainCollectionView.backgroundColor = [UIColor clearColor];

    //3.注册collectionViewCell
    //注意,此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [mainCollectionView registerClass:[AppListCollectCell class] forCellWithReuseIdentifier:@"cellId"];

    //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
    [mainCollectionView registerClass:[HomeCollectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    //设置代理
    mainCollectionView.delegate = self;
    mainCollectionView.dataSource = self;
}

#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 9;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AppListCollectCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cellId" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

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

//header的size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(ScreenWidth, 40);
}

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

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


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

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view,其中 ReuseIdentifier 的值必须和 注册是填写的一致,本例都为 “reusableView”
#pragma mark -- 返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HomeCollectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"offlineID" forIndexPath:indexPath];
            header.headeLab.text = [dict objectForSafeKey:@"组头"];
        reusableView = header;
    }
    //如果是头视图
    return reusableView;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSString *msg = cell.botlabel.text;
    NSLog(@"%@",msg);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
展开阅读全文

没有更多推荐了,返回首页