iOS Developer

iOS 纯代码搭建collectionView

2016-12-14  本文已影响155人  Just_go

因为项目中常会用到collectionView, 特地总结了一下必要的步骤, 方便自己以后查阅, 大家也可以在此基础上自行扩展成瀑布流之类.

第一步. 创建流水布局
在ViewController.m中

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define Margin 10
#define itemWH  (ScreenWidth - 4 * Margin)/3

static NSString *ID = @"cell";
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //流水布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    layout.minimumLineSpacing = Margin;
    layout.minimumInteritemSpacing = Margin;
    
    //创建collectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenWidth) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:collectionView];
    
    //设置数据源
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [collectionView registerClass:[SquareCell class] forCellWithReuseIdentifier:ID];
}

注意点: 最后一定要注册cell, 如果是xib的话, 调registerNib方法

第二部:实现代理和数据源方法

#pragma mark -- UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 9;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.tailLabel.text = [NSString stringWithFormat:@"我是第%ld个",(long)indexPath.row];
    return cell;
}

使用要点和tableView一样,会tableView就会collectionView

第三步: 搭建cell
在squareCell.m中

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define Margin 10
#define itemWH  (ScreenWidth - 4 * Margin)/3

#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))

@implementation SquareCell

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self creatView];
    }
    return self;
}

-(void)creatView{
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, itemWH, itemWH - 20)];
    iconImageView.backgroundColor = randomColor;
    [self addSubview:iconImageView];
    
    UILabel *tailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, itemWH - 15, itemWH, 15)];
    tailLabel.textAlignment = NSTextAlignmentCenter;
    _tailLabel = tailLabel;
    [self addSubview:_tailLabel];
}

当然这里用到了一个比较实用的宏randomColor, 大家也可以记下以备不时之需.
效果图:


Snip20161214_3.png
上一篇下一篇

猜你喜欢

热点阅读