在iOS6.0之后,苹果退出了一个新的继承于UIScrollView的一个视图,UICollectionView,也被称为集合视图。和UITableView共同作为在开发中非常常用的两个视图,常常作为项目的主界面出现。

集合视图的数据源协议UICollectionViewDataSource
@protocol UICollectionViewDataSource <NSObject>
两个必须实现的方法
@required
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
可选的方法
@optional
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
添加增广视图的方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
@end
集合视图的代理协议UICollectionDelegate

添加增广视图
增广视图里没有东西,需要自定义创建一个继承 UICollectionReusableView
//返回增广视图,就是集合视图的头视图和尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//第一个参数dequeueReusableSupplementaryViewOfKind 标记返回头还是尾视图
YouCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
view.backgroundColor = [UIColor yellowColor];
view.headLabel.text = [NSString stringWithFormat:@"当前分区为:%ld",indexPath.section];
return view;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//第一个参数dequeueReusableSupplementaryViewOfKind 标记返回头还是尾视图
YouCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
view.backgroundColor = [UIColor yellowColor];
view.headLabel.text = [NSString stringWithFormat:@"当前分区为:%ld",indexPath.section];
return view;
}

浙公网安备 33010602011771号