实现协议 .h中
@interface HomeViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@end
具体实现 .m
@interface HomeViewController ()
@end
UICollectionView *collectionView;
NSString *identifier = @"cellectionCell";
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];//初始化要设置一个flowlayout
collectionView.delegate = self;//设置代理
collectionView.dataSource = self;//设置数据源
collectionView.backgroundColor = [UIColor grayColor];
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];// 注册缓存标准
[self.view addSubview:collectionView];
}
//单元格数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return items.count;
}
//选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
backItem.title = @"返回";
self.navigationItem.backBarButtonItem = backItem;
[self.navigationController pushViewController:[[items objectAtIndex:indexPath.row] objectForKey:@"vc"] animated:YES];
}
//具体单元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height - 30)];
image.contentMode = UIViewContentModeScaleAspectFill;
[image setImage:[UIImage imageNamed:@"ic_launcher"]];
CGFloat imageY = CGRectGetMaxY(image.frame);
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, imageY, cell.frame.size.width, 30)];
title.text = [[items objectAtIndex:indexPath.row] objectForKey:@"title"];
[cell addSubview:image];
[cell addSubview:title];
return cell;
}
//分组数量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//每个cell的大小
- (CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
float width = [[UIScreen mainScreen] bounds].size.width / 3 - 15;
return CGSizeMake(width, width + 30);
}
//距边界缩放大小
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(10, 10, 10, 10);//分别为上、左、下、右
}