UICollectionView学习<1>之UICollectionView的简单使用

注意:
使用UICollectionView时必须要:

  • UICollectionView设置布局;
  • UICollectionViewCell注册;

一.使用StoryBoard

首先在StoryBoard中创建一个UICollectionViewController,让与其绑定的控制器类继承自UICollectionViewController,然后在控制器类中对UICollectionViewCell进行注册、并且适当地实现UICollectionViewDelegateUICollectionViewDatasourceUICollectionViewDelegateFlowLayout协议中的方法,这样便可简单地实现对UICollectionView的简单使用。记住:这种方法布局默认是设置好的。

二.使用纯代码实现:

1.控制器类继承自UICollectionViewController(已经帮我们实现了UICollectionView的协议)
注意:UICollectionViewController默认是没有设置UICollectionView的布局的,因此需要我们在创建UICollectionView之前为它制定布局。方法是重写父类UICollectionViewController中的-(void)init方法,在其中设置布局:

- (instancetype)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(60, 60);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    return [super initWithCollectionViewLayout:layout];
}

2.在普通的视图控制器中添加UICollectionView(我们要手动实现UICollectionView的协议)

#import <UIKit/UIKit.h>

@interface ViewController :UIViewController
@property(nonatomic,strong)UICollectionView* collectionView;

@end
#import "ViewController.h"
 static  NSString* const ID=@"cell";
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor orangeColor];
    self.collectionView=[[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate=self;
    self.collectionView.dataSource=self;
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark -数据源方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值