为了增强网格视图开发.从iOS6开始,就开放集合视图API(collectionView).它有4个重要部分组成.
单元格:它是集合视图中的一个单元格
节:它是集合视图中的一个行数据,由多个单元格构成
补充视图:它是节的头和脚
装饰视图:集合视图中的背景视图
UICollectionView继承UIScrollView,与选择器类似,集合视图有两个协议;UICollectionViewDelegate委托协议和UICollectionViewDataSource数据源协议.
下面是例子
创建一个Single View Application项目
将viewController改为继承自UICollectionViewController
在main.storyboard中添加一个CollectionView.为方便查看,将背景颜色改为白色,并添加dataSource和delegate协议方法.
选中UIcollectionViewCell设置大小,并在上面添加需要的控件.至此界面设计完毕,开始代码工作.
images/loading.gif' data-original="http://images2015.cnblogs.com/blog/809898/201509/809898-20150929201805840-563551476.png" />
创建类继承自UICollectionViewCell,命名为myCell,不要忘了把他同设计界面的cell关联
因为cell我们不需要显示太多,所以先完成cel
@property (weak, nonatomic) IBOutlet UIImageView *imageView;@property (weak, nonatomic) IBOutlet UILabel *label;
//初始化init方法
-(id)initWithFrame:(CGRect)frame{ self=[super initWithFrame:frame]; if (self) { } return self;}
完成myCell类的工作后,我们继续viewContrller工作
创建数据源数组
@property(nonatomic,retain)NSMutableArray *array;
初始化数据源数组,这里使用的数据来自一个plist文件,plist文件包括名字与图片
_array=[[NSMutableArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"events" ofType:@"plist"]];
接着是完成代理方法(一**代码来袭)
#pragma mark ---UICollectionViewDataSource---//多少个节-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return _array.count/2;}//设置每行显示个数-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return 2;}//创建单元格-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ myCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; NSDictionary *event=[_array objectAtIndex:(indexPath.section*2 +indexPath.row)]; cell.label.text=[event objectForKey:@"name"]; cell.imageView.image=[UIImage imageNamed:[event objectForKey:@"image"]]; return cell;}#pragma mark---UICollectionViewDelegate---//点击事件-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ NSDictionary *event=[self.array objectAtIndex:(indexPath.section*2+indexPath.row)]; NSLog(@"select event name : %@", [event objectForKey:@"name"]);}
就喜欢这种复制粘贴的感觉
运行后效果如图:
原标题:UICollectionViewController
关键词:ie