1. #import "ViewController.h"
  2. #import "CollectionViewCell.h"
  3. @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
  4. @property (weak, nonatomic) IBOutlet UICollectionView *collectionCell;
  5.  @end

 

  1. @implementation ViewController
  2. - (void)viewDidLoad
  3. {
  4.     [super viewDidLoad];
  5.     self.collectionCell.backgroundColor = [UIColor greenColor];
  6.     self.collectionCell.dataSource = self;
  7.     self.collectionCell.delegate = self;
  8. #pragma mark -- UICollectionViewDataSource
  9. //设置collectionCell的个数
  10. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  11. {
  12.     return 9;
  13. }
  14. //定义展示的Section的个数
  15. -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  16. {
  17.     return 1;
  18. }
  19. //每个UICollectionView展示的内容
  20. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  21. {
  22.     //使用collectionCell进行注册,通过xib文件加载视图
  23.     [self.collectionCell registerNib:[UINib nibWithNibName:@"myCell" bundle:nil]
  24.           forCellWithReuseIdentifier:@"mycell"];
  25.     CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"mycell" forIndexPath:indexPath];
  26.     //图片名称
  27.     NSString *imageToLoad = [NSString stringWithFormat:@"%ld.jpg", indexPath.row];
  28.     //加载图片
  29.     cell.iamgeView.image = [UIImage imageNamed:imageToLoad];
  30.     //设置label文字
  31.     cell.labeiInfo.text = [NSString stringWithFormat:@"image%ld",indexPath.row];
  32.     return cell;
  33. }
  34. //设置每个各自的大小
  35. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  36. {
  37.     return CGSizeMake(170, 170);
  38. }
  39.  //定义每个UICollectionView 的 margin
  40. -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  41. {
  42.     return UIEdgeInsetsMake(5, 5, 5, 5);
  43. }
  44.  //UICollectionView被选中时调用的方法
  45. -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  46. {
  47.     UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
  48.     cell.backgroundColor = [UIColor whiteColor];
  49. }
  50. //返回这个UICollectionView是否可以被选择
  51. -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
  52. {
  53.     return YES;
  54. }
  55. //隐藏状态栏
  56. -(BOOL)prefersStatusBarHidden
  57. {
  58.     return YES;
  59. }
  60. @end

程序运行结果: