注意:
使用UICollectionView时必须要:
- 为
UICollectionView
设置布局; - 为
UICollectionViewCell
注册;
一.使用StoryBoard
:
首先在StoryBoard
中创建一个UICollectionViewController
,让与其绑定的控制器类继承自UICollectionViewController
,然后在控制器类中对UICollectionViewCell
进行注册、并且适当地实现UICollectionViewDelegate
、UICollectionViewDatasource
、UICollectionViewDelegateFlowLayout
协议中的方法,这样便可简单地实现对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