collectionView的案例

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

程序运行结果:

 

posted @ 2015-09-09 08:13  Mr·Xu  阅读(181)  评论(0)    收藏  举报