collectionView的案例
- #import "ViewController.h"
- #import "CollectionViewCell.h"
- @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
- @property (weak, nonatomic) IBOutlet UICollectionView *collectionCell;
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.collectionCell.backgroundColor = [UIColor greenColor];
- self.collectionCell.dataSource = self;
- self.collectionCell.delegate = self;
- }
- #pragma mark -- UICollectionViewDataSource
- //设置collectionCell的个数
- -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- {
- return 9;
- }
- //定义展示的Section的个数
- -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
- {
- return 1;
- }
- //每个UICollectionView展示的内容
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- //使用collectionCell进行注册,通过xib文件加载视图
- [self.collectionCell registerNib:[UINib nibWithNibName:@"myCell" bundle:nil]
- forCellWithReuseIdentifier:@"mycell"];
- CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"mycell" forIndexPath:indexPath];
- //图片名称
- NSString *imageToLoad = [NSString stringWithFormat:@"%ld.jpg", indexPath.row];
- //加载图片
- cell.iamgeView.image = [UIImage imageNamed:imageToLoad];
- //设置label文字
- cell.labeiInfo.text = [NSString stringWithFormat:@"image%ld",indexPath.row];
- return cell;
- }
- //设置每个各自的大小
- -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return CGSizeMake(170, 170);
- }
- //定义每个UICollectionView 的 margin
- -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
- {
- return UIEdgeInsetsMake(5, 5, 5, 5);
- }
- //UICollectionView被选中时调用的方法
- -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
- cell.backgroundColor = [UIColor whiteColor];
- }
- //返回这个UICollectionView是否可以被选择
- -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return YES;
- }
- //隐藏状态栏
- -(BOOL)prefersStatusBarHidden
- {
- return YES;
- }
- @end
程序运行结果: