iOS:如何使用UICollectionView

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


#import "ViewController.h"

static NSString *cellID = @"cell";

@interface ViewController ()
@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
  • 运行效果图如下:
iOS:如何使用UICollectionView_第1张图片
Snip20161213_76.png
  • 注意
    在使用UICollectionView时,有别于UITableView,特别注意使用UICollectionView时,一定要注册cell,如果不注册(代码如下),就会报错,如下图
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 不能直接创建cell,一定要注册,否则报错
    UICollectionViewCell *cell = [[UICollectionViewCell alloc] init];
    cell.backgroundView.backgroundColor = [UIColor purpleColor];
    return cell;
}
  • 报错如下


    iOS:如何使用UICollectionView_第2张图片
    Snip20161213_73.png

你可能感兴趣的:(iOS:如何使用UICollectionView)