1。在控制器的viewDidLoad方法中添加代码
CGFloat itemWidth = (kScreenW - kSpacingW * 3) / 2;
NSLog(@"itemWidth == %f",itemWidth);
CGFloat itemHeight = itemWidth * 0.75 + 71;
NSLog(@"itemWidth == %f",itemHeight);
UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(itemWidth, itemHeight);
layout.minimumInteritemSpacing = kSpacingW;
layout.minimumLineSpacing = kSpacingW;
layout.sectionInset = UIEdgeInsetsMake(0, kSpacingW, 0, kSpacingW);
self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
[self.view addSubview:self.collectionView];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerClass:[HotCell class] forCellWithReuseIdentifier:@"HotCell"];
2.实现collectionView的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
HotCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
3.通过XIB自定义cell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 初始化时加载collectionCell.xib文件
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"HotCell" owner:self options:nil];
// 如果路径不存在,return nil
if (arrayOfViews.count < 1) {
return nil;
}
// 如果xib中view不属于UICollectionViewCell类,return nil
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
// 加载nib
self = [arrayOfViews objectAtIndex:0];
}
return self;
}