iOS技术中心iOS Developer

iOS:如何使用UICollectionView

2016-12-13  本文已影响73人  IMKel

本文章主要教大家UICollectionView最最基本的使用,笔者使用纯代码编写代码
UICollectionView基本使用:请看viewController.m文件中的代码,写完这些代码,你就算是会使用UICollectionView了


#import "ViewController.h"

static NSString *cellID = @"cell";

@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong) UICollectionView *myCollectionView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGRect collectionViewFrame= CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    flowLayout.minimumLineSpacing = 1;// 根据需要编写
//    flowLayout.minimumInteritemSpacing = 1;// 根据需要编写
//    flowLayout.itemSize = CGSizeMake(70, 70);// 该行代码就算不写,item也会有默认尺寸
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor redColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    _myCollectionView = collectionView;
    [self.view addSubview:collectionView];
    
    [self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellID];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 30;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    if (!cell ) {
        NSLog(@"cell为空,创建cell");
        cell = [[UICollectionViewCell alloc] init];
    }
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

@end
Snip20161213_76.png
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 不能直接创建cell,一定要注册,否则报错
    UICollectionViewCell *cell = [[UICollectionViewCell alloc] init];
    cell.backgroundView.backgroundColor = [UIColor purpleColor];
    return cell;
}
上一篇下一篇

猜你喜欢

热点阅读