實(shí)現(xiàn)協(xié)議 .h中
@interface HomeViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@end
具體實(shí)現(xiàn) .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]];//初始化要設(shè)置一個(gè)flowlayout
collectionView.delegate = self;//設(shè)置代理
collectionView.dataSource = self;//設(shè)置數(shù)據(jù)源
collectionView.backgroundColor = [UIColor grayColor];
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];// 注冊(cè)緩存標(biāo)準(zhǔn)
[self.view addSubview:collectionView];
}
//單元格數(shù)量
- (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;
}
//分組數(shù)量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//每個(gè)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);//分別為上、左兢仰、下、右
}