#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建流布局对象 (保存设定的样式规则)
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
// 设定单元格的大小
flow.itemSize = CGSizeMake(90, 140);
// 设定滚动方向
flow.scrollDirection = UICollectionViewScrollDirectionVertical;
// 最小列间距
flow.minimumInteritemSpacing = 20;
// 最小行间距
flow.minimumLineSpacing = 20;
// 设定分区的边距
//UIEdgeInsetsMake30(从屏幕最上方下降30), 20(网格从屏幕左边偏移20), 20(从屏幕底部下方距离为20), 20(网格从屏幕右边偏移20);
flow.sectionInset = UIEdgeInsetsMake(30, 20, 20, 20);
// 创建网格对象,用流布局对象进行初始化
UICollectionView *collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flow];
// 设定代理关系
collect.dataSource = self;
collect.delegate = self;
collect.pagingEnabled = YES;
collect.backgroundColor = [UIColor whiteColor];
// 将网格加入到视图上显示
[self.view addSubview:collect];
// 为网格注册单元格类
[collect registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 20;
}
// 单元格内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.backgroundColor =[UIColor orangeColor];
// 设置显示数据
cell.img.image = [UIImage imageNamed:@"wd.jpg"];
cell.textLab.text = @"叶良辰";
cell.textfs.text = @"10w粉丝";
return cell;
}
@end
CollectionViewCell.h
#import <UIKit/UIKit.h>
@interface CollectionViewCell : UICollectionViewCell
// 图片
@property (nonatomic,strong) UIImageView *img;
// 文字
@property (nonatomic,strong) UILabel *textLab;
//粉丝
@property (nonatomic,strong) UILabel * textfs;
@end
CollectionViewCell.m
#import "CollectionViewCell.h"
@implementation CollectionViewCell
- (UIImageView *)img
{
if (_img == nil)
{
_img = [[UIImageView alloc]initWithFrame:CGRectMake(15, 20, 60, 60)];
[self addSubview:_img];
}
return _img;
}
//
- (UILabel *)textLab
{
if (_textLab == nil)
{
_textLab = [[UILabel alloc] initWithFrame:CGRectMake(5, 90, 80, 20)];
_textLab.textAlignment = NSTextAlignmentCenter;
_textLab.textColor= [UIColor redColor];
[self addSubview:_textLab];
}
return _textLab;
}
-(UILabel * )textfs
{
if (_textfs == nil)
{
_textfs = [[UILabel alloc]initWithFrame:CGRectMake(5, 120, 80, 20)];
_textfs.textAlignment = NSTextAlignmentCenter;
_textfs.textColor = [UIColor redColor];
[self addSubview:_textfs];
}
return _textfs;
}
@end