1、實現(xiàn)代理
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@end
2码党、聲明UICollectionView
@property (nonatomic, strong) UICollectionView *myCollectionView;
3、實現(xiàn)代理方法
/**
*數(shù)據(jù)源代理
*/
//返回個數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 50;
}
//返回單元格,自定義單元格很重要的部分
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cid forIndexPath:indexPath];
cell.backgroundColor = [UIColor orangeColor];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
imageView.image = [UIImage imageNamed:@"image.jpg"];
[cell.contentView addSubview:imageView];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 35, 100, 40)];
label.text = @"路飛";
label.textColor = [UIColor whiteColor];
[cell.contentView addSubview:label];
return cell;
}
/**
*布局代理
*/
//設置邊距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(0, 0, 0, 0);
}
//設置item寬高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(self.myCollectionView.bounds.size.width, 80);
}
//選擇item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
NSLog(@"選中了---> %lu", indexPath.row);
}
//點擊后的item
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor orangeColor];
}
4置蜀、綁定View
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//布局
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
//創(chuàng)建CollectionView
self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(20, 30, self.view.bounds.size.width-40, self.view.bounds.size.height-60) collectionViewLayout:flowLayout];
//注冊Cell單元
[self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cid];
self.myCollectionView.dataSource = self;
self.myCollectionView.delegate = self;
self.myCollectionView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.myCollectionView];
}