<UICollectionViewDelegate,UICollectionViewDataSource>{
UICollectionView *collectionV;
}//创建一个布局对象
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//设置单元格大小
flowLayout.itemSize=CGSizeMake(100,100);
flowLayout.sectionInset=UIEdgeInsetsMake(80,10,0,10);
flowLayout.minimumInteritemSpacing = 20;
flowLayout.minimumLineSpacing=20;
collectionV = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
collectionV.delegate = self;
collectionV.dataSource = self;
collectionV.backgroundColor = [UIColor cyanColor];
[collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
[self.view addSubview:collectionV];
}
//数据源方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView{
return 5;
}
-(NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section{
return 7;
}
//设置cell
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
//根据可重用标识符查找cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.backgroundColor= [UIColorpurpleColor];
cell.imgView.image= [UIImageimageNamed:@"9"];
cell.layer.borderWidth = 1;
returncell;
}
定义自定义网格视图
.h@property (nonatomic,strong) UIImageView *imgView;
- (instancetype)initWithFrame:(CGRect)frame
{
self= [superinitWithFrame:frame];
if(self) {
[selfaddSubview:self.imgView];
}
return self;
}
// 重写 GET 方法
- (UIImageView*)imgView
{
if (!_imgView)
{
_imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
}
return _imgView;
}
网友评论