多行多列控件:UICollectionView

来源:互联网 发布:古诗词制作软件 编辑:程序博客网 时间:2024/06/03 22:01

本章通过先总体介绍UICollectionView及其常用方法,再结合一个实例,了解如何使用UICollectionView。

 

UICollectionView 和 UICollectionViewController 类是iOS6 新引进的API,用于展示集合视图,布局更加灵活,可实现多列布局,用法类似于UITableView 和 UITableViewController 类。

使用UICollectionView 必须实现UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout这三个协议。

 

下面先给出常用到的一些方法。(只给出常用的,其他的可以查看相关API) 

  1. #pragma mark -- UICollectionViewDataSource   
  1. //定义展示的UICollectionViewCell的个数  
  2. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  
  3. {  
  4.     return 30;  
  5. }   
  1. //定义展示的Section的个数  
  2. -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  
  3. {  
  4.     return 1;  
  5. }   
  1. //每个UICollectionView展示的内容  
  2. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath  
  3. {  
  4.     static NSString * CellIdentifier = @"GradientCell";  
  5.     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];  
  6.   
  7.     cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];  
  8.     return cell;  
  9. }   
  1. #pragma mark --UICollectionViewDelegateFlowLayout   
  1. //定义每个UICollectionView 的大小  
  2. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath  
  3. {  
  4.     return CGSizeMake(96, 100);  
  5. }   
  1. //定义每个UICollectionView 的 margin  
  2. -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section  
  3. {  
  4.     return UIEdgeInsetsMake(5, 5, 5, 5);  
  5. }   
  1. #pragma mark --UICollectionViewDelegate   
  1. //UICollectionView被选中时调用的方法  
  2. -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  
  3. {  
  4.     UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];  
  5.     cell.backgroundColor = [UIColor whiteColor];  
  6. }   
  1. //返回这个UICollectionView是否可以被选择  
  2. -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath  
  3. {  
  4.     return YES;  
  5. }  

  layout.minimumInteritemSpacing = 0;//每列最小边距
    layout.minimumLineSpacing = 0;//每行最小边距 

 

下面通过一个例子具体介绍下。(例子来自网络。但是是通过第三方获得的,无法取得链接。还望见谅。)

 

iOS CollectionView的出现是一大福利,再也不用用TableView来定义复杂的多栏表格了,用法与Table类似,只是Cell必须自己添加,无默认模式

由于CollectionView没有默认的Cell布局,所以一般还是自定义方便又快捷

一、自定义Cell

1、新建类CollectionCell继承自UICollectionViewCell

2、新建Xib,命名为CollectionCell.xib

a.选中CollectionCell.xib删掉默认的View,从控件中拖一个Collection View Cell(图3)到画布中,设置大小为95*116

 

b.选中刚刚添加的Cell,更改类名为CollectionCell,如图4

c.在CollectionCell.xib的CollectionCell中添加一个ImageView和一个Label(图5)

d.创建映射, 图6,图7

e.选中CollectionCell.m , 重写init方法 

  1. - (id)initWithFrame:(CGRect)frame  
  2. {  
  3.     self = [super initWithFrame:frame];  
  4.     if (self)  
  5.     {  
  6.         // 初始化时加载collectionCell.xib文件  
  7.         NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options:nil];  
  8.           
  9.         // 如果路径不存在,return nil  
  10.         if (arrayOfViews.count < 1)  
  11.         {  
  12.             return nil;  
  13.         }  
  14.         // 如果xib中view不属于UICollectionViewCell类,return nil  
  15.         if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]])  
  16.         {  
  17.             return nil;  
  18.         }  
  19.         // 加载nib  
  20.         self = [arrayOfViews objectAtIndex:0];  
  21.     }  
  22.     return self;  
  23. }  


f.选中CollectionCell.xib 修改其identifier为CollectionCell。


二、定义UICollectionView;

1、拖动一个Collection View到指定ViewController的View上

2、连线dataSource和delegate,并创建映射,命名为CollectionView

3、选中CollectionView的标尺,将Cell Size的Width和Height改成与自定义的Cell一样的95*116,图8

    

4、选中CollectionView的属性,可以修改其属性,比如是垂直滑动,还是水平滑动,选择Vertical或Horizontal

5、选中CollectionViewCell,修改Class,继承自CollectionCell

5、在ViewDidLoad方法中声明Cell的类,在ViewDidLoad方法中添加,此句不声明,将无法加载,程序崩溃

其中,CollectionCell是这个Cell的标识(之前几步已经定义过了。 ) 

  1. [self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];  


6、在ViewController.h中声明代理 

  1. @interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>  



 

7、在.m文件中实现代理方法 

  1. //每个section的item个数  
  2. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  
  3. {  
  4.     return 12;  
  5. }  
  6.   
  7. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath  
  8. {  
  9.       
  10.     CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];  
  11.       
  12.     //图片名称  
  13.     NSString *imageToLoad = [NSString stringWithFormat:@"%d.png", indexPath.row];  
  14.     //加载图片  
  15.     cell.imageView.image = [UIImage imageNamed:imageToLoad];  
  16.     //设置label文字  
  17.     cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.row,(long)indexPath.section];  
  18.       
  19.     return cell;  
  20. }  



 

8 。效果如图10

点击某项后跳转事件与UITableView类似,实现代理方法 

  1. -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  

即可,不赘述


代码创建

swift

 let flowLayout =UICollectionViewFlowLayout()

        flowLayout.itemSize =CGSizeMake(UIScreen.mainScreen().bounds.size.width,100)

        flowLayout.scrollDirection =UICollectionViewScrollDirection.Vertical//设置垂直显示

        flowLayout.sectionInset =UIEdgeInsetsMake(0,1,0,1)//设置边距

        flowLayout.minimumLineSpacing =0.0;//每个相邻layout的上下

        flowLayout.minimumInteritemSpacing =0.0;//每个相邻layout的左右

        flowLayout.headerReferenceSize =CGSizeMake(0,0);

        

        self.siteCollect =UICollectionView(frame:CGRectMake(0,270,100,100), collectionViewLayout: flowLayout)

        self.siteCollect!.setTranslatesAutoresizingMaskIntoConstraints(false)

        self.siteCollect!.backgroundColor =UIColor.whiteColor()

        self.siteCollect!.alwaysBounceVertical =true

        self.siteCollect!.delegate =self

        self.siteCollect!.dataSource =self

        self.view.addSubview(self.siteCollect!)

        self.siteCollect!.registerClass(SiteDetailCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")


Object-C

//初始化是这样初始化的。
-(void) initCollectionView{
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize=CGSizeMake(100,100);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
     
    _gridView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, 410)];
    _gridView.dataSource=self;
    _gridView.delegate=self;
    [_gridView setBackgroundColor:[UIColor blueColor]];
    [_gridView setCollectionViewLayout:flowLayout];
     
    [_gridView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewIdentifier"];
     
    [self.view addSubview:_gridView];
}


初始化:

//初始化布局类(UICollectionViewLayout的子类)
UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];

//初始化collectionView
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];

//设置代理
self.collectionView.delegate = self;
self.collectionView.dataSource = self;

--------------------

需要实现的协议:
UICollectionViewDataSourceUICollectionViewDelegateFlowLayout
PS:UICollectionViewDelegateFlowLayoutUICollectionViewDelegate的子协议

--------------------

注册相应的UICollectionViewCell子类到collectionView用来从队列提取和显示
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
PS:如果是用nib创建的话,使用下面这个函数来注册。
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;

如果需要显示每个section的headerView或footerView,则还需注册相应的UICollectionReusableView的子类到collectionView
elementKind是header或footer的标识符,只有两种可以设置UICollectionElementKindSectionHeader和UICollectionElementKindSectionFooter
- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
PS:如果是用nib创建的话,使用下面这个函数来注册。
- (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;

--------------------

实现协议的函数:
跟UITableView的DataSource和Delegate很像,大可自行代入理解。

DataSource:

//每一组有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;

//定义并返回每个cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

//collectionView里有多少个组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;

//定义并返回每个headerView或footerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

上面这个方法使用时必须要注意的一点是,如果布局没有为headerView或footerView设置size的话(默认size为CGSizeZero),则该方法不会被调用。所以如果需要显示header或footer,需要手动设置size。
可以通过设置UICollectionViewFlowLayout的headerReferenceSize和footerReferenceSize属性来全局控制size。或者通过重载以下代理方法来分别设置
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;

Delegate:

//每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

//设置每组的cell的边界, 具体看下图
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;

142014942.png

142045183.png



//cell的最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;

//cell的最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

//cell被选择时被调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;

//cell反选时被调用(多选时才生效)
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;

本文出自 “rainbownight” 博客,请务必保留此出处http://rainbownight.blog.51cto.com/1336585/1323780



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 大车一次扣12分怎么办 a2驾照扣10分怎么办 驾驶证强制降级没给驾驶证怎么办 6P升11.2卡了怎么办 b2驾照记满12分怎么办 c1驾驶证没分了怎么办 驾照扣了15分怎么办 驾驶证暂扣六个月后怎么办 醉驾交警不通知怎么办 参军后地方驾驶证年审怎么办 军人驾驶证到期身份证注销了怎么办 资格证脱审30天怎么办 驾驶证c证扣6分怎么办 驾照被扣了9分怎么办 驾驶证被扣了9分怎么办 a2驾驶本扣3分怎么办 c1e没过扣了满分怎么办 c1一下扣12分怎么办 换证体检过不了怎么办 唐山驾驶本到期换本怎么办 北京居住证变更地址了怎么办 眼睛弱视驾驶证换证不了怎么办? 驾照的分扣完了怎么办 驾照被扣了3分怎么办 交警扣了行驶证怎么办 报考驾照时手机号录错怎么办 摩托车被交警队拖走怎么办 汽车牌照被偷了怎么办 代理品牌个体工商营业证怎么办 2地交社保怎么办退休 驾驶证脱审3月怎么办 a1一次性扣12分怎么办 驾照在外地掉了怎么办 在外市考的驾照怎么办 驾照过期3个月怎么办 驾照过期6个月怎么办 b本扣分了6分怎么办 b2驾照提前换证有扣分怎么办 酒驾驾驶证被扣怎么办 驾驶证被扣了分怎么办 c1驾照扣了12分怎么办