// ViewController.h // UI2_UICollectionViewPicture // // Created by zhangxueming on 15/7/16. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end // // ViewController.m // UI2_UICollectionViewPicture // // Created by zhangxueming on 15/7/16. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import "ViewController.h" #define kCellReuseId @"cellID" @interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate> { UICollectionView *_collectionView; NSMutableArray *_dataList; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //创建数据源 [self createDataList]; //创建UI [self createUI]; //代理 self.navigationController.navigationBar.barTintColor = [UIColor redColor]; } - (void)createDataList { _dataList = [NSMutableArray array]; for (int i=0; i<10; i++) { NSString *name = [NSString stringWithFormat:@"superCar%i", i]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"]; UIImage *image = [UIImage imageWithContentsOfFile:path]; [_dataList addObject:image]; } } //创建UI - (void)createUI { //创建布局对象 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; //上下左右边距 layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); //cell的大小 layout.itemSize = CGSizeMake(150, 100); //cell横向间距 layout.minimumInteritemSpacing = 20; //cell纵向间距 layout.minimumLineSpacing = 30; //创建collectionView _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; _collectionView.backgroundColor = [UIColor whiteColor]; //设置代理 _collectionView.delegate = self; _collectionView.dataSource = self; //注册cell [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellReuseId]; [self.view addSubview:_collectionView]; } #pragma mark ---delegate--- //返回分区个数 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } //返回分区cell 的个数 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return _dataList.count; } //返回cell - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellReuseId forIndexPath:indexPath]; for (UIView *view in cell.contentView.subviews) { [view removeFromSuperview]; } UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 100)]; imageView.image = _dataList[indexPath.item]; [cell.contentView addSubview:imageView]; return cell; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
转载于:https://www.cnblogs.com/0515offer/p/4652467.html