集合视图UICollectionView

2017-04-12  本文已影响51人  Kevin_wzx

1.概念

iOS6引入了集合视图(UICollectionView),它是一种网格状视图,其功能远远超越了标准的表格视图。集合视图的很多概念与表格视图相同,但更加强大和灵活。开发者可以利用集合视图创建出横向滚动的列表、网络以及特殊的布局。集合视图和表格视图的比较如下:

屏幕快照 2017-04-12 上午9.36.46.png

补充:UICollectionView的使用相当于其他的视图可能是比较复杂的,但是它也是功能最强大的,它的出现使得原来需要用滚动视图和表格视图来定制的东西基本上都可以使用集合视图进行定制,而且能够做出更好的效果。例如通过自定义布局管理器可以实现将单元格排列成一个圆,这种效果在很多地方都可以见到了。如果希望对UICollectionView有一个更深刻的了解,我们推荐阅读《iOS核心开发手册》一书,上面有更为详细的讲解。

2.基本用法

UICollectionView的基本用法可以参照使用UITableView的步骤,如下所示

#import "ViewController.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height

#define NAME @"火影忍者"

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> {

    // 集合视图
    UICollectionView *myCollView;
    // 保存数据模型的数组
    NSMutableArray *dataArray;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = NAME;

    // 创建一个流式布局管理
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置滚动方向为垂直方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 设置单元格的最小水平间距
    layout.minimumInteritemSpacing = 10;
    // 设置最小行间间距
    layout.minimumLineSpacing = 10;
    // 指定单元格的尺寸 (大小)
     layout.itemSize = CGSizeMake(100, 150);
    // 设置内边距(上左下右)
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);

    // 创建集合视图
    myCollView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) collectionViewLayout:layout];
    [self.view addSubview:myCollView];
    // 设置集合视图透明背景色
    myCollView.backgroundColor = [UIColor clearColor];

    // 绑定委托和数据源
    myCollView.delegate = self;
    myCollView.dataSource = self;

    // 注册可复用单元格
    [myCollView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CELL"];

    // 加载数据模型
    [self loadDataModel];
}

- (void) loadDataModel {
    if (!dataArray) {
        NSString *filename = [[NSBundle mainBundle] pathForResource:NAME ofType:@"plist"];
        dataArray = [NSMutableArray arrayWithContentsOfFile:filename];
    }
}

// 获得分区中有多少个单元格的回调方法
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return dataArray.count;
}

// 创建集合视图每个单元格的回调方法
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 获得可重用单元格
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    // 获得数据模型中取出图片的名称并获得其路径
    NSDictionary *dict = dataArray[indexPath.row];
    NSString *filename = [[NSBundle mainBundle] pathForResource:dict[@"imageName"] ofType:nil];
    // 根据图片名称获得UIImage对象
    UIImage *image = [UIImage imageWithContentsOfFile:filename];
    // 创建一个UIImageView对象添加到单元格的contentView中以显示UIImage
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 100, 150);
    [cell.contentView addSubview:imageView];

    return cell;
}

@end

效果如图:

20151216233447984.png

备注:如果你留心程序在运行时的表现,你可能会发现一个非常严重的bug,就是随着你在集合视图中上线滚动,程序占用的内存会迅速攀升,程序开始出现卡顿现象,这一点可以通过debug导航中的Memory项得到证实,如下图所示。另一方面,你也可以打开"Debug View Hierarchy"看到问题产生的原因。

屏幕快照 2017-04-12 上午9.54.58.png
要修正这个问题其实很简单,在创建集合视图单元格的时候不能每次都向单元格的contentView中添加UIImageView的对象,如果contentView中已经有UIImageView,直接修改UIImageView的image属性就可以刷新视图了,修正的代码如下所示:
// 创建集合视图每个单元格的回调方法
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // 获得可重用单元格
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    // 获得数据模型中取出图片的名称并获得其路径
    NSDictionary *dict = dataArray[indexPath.row];
    NSString *filename = [[NSBundle mainBundle] pathForResource:dict[@"imageName"] ofType:nil];

    UIImageView *imageView = (id)[cell viewWithTag:1000];
    if (!imageView) {
        // 创建一个UIImageView对象添加到单元格的contentView中以显示UIImage
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 150)];
        imageView.tag = 1000;
        [cell.contentView addSubview:imageView];
    }
    imageView.image = [UIImage imageWithContentsOfFile:filename];
    return cell;
}

3.集合视图的单元格定制

进一步对UICollectionView进行定制,例如像表格视图一样定制每个分段的头和尾,定制每个单元格的尺寸以及单元格中的子视图,且看下面的例子

屏幕快照 2017-04-12 上午10.04.44.png 屏幕快照 2017-04-12 上午10.05.13.png 屏幕快照 2017-04-12 上午10.09.45.png 屏幕快照 2017-04-12 上午10.09.57.png 屏幕快照 2017-04-12 上午10.10.06.png
其中,可重用单元格的代码如下所示:
#import <UIKit/UIKit.h>

@interface CDMyCollectionViewCell : UICollectionViewCell {
    UILabel *label;
}

@property (nonatomic, copy) NSString *model;

@end

#import "CDMyCollectionViewCell.h"

@implementation CDMyCollectionViewCell

- (void)setModel:(NSString *)model {
    _model = model;
    if (!label) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        label.textAlignment = NSTextAlignmentCenter;
        label.adjustsFontSizeToFitWidth = YES;
        self.layer.borderWidth = 1;
        [self.contentView addSubview:label];
    }
    label.text = model;
}

@end

效果如图:

20151216235346034.png

4.利用集合视图实现横向无限滚动

用集合视图实现一个无限循环轮播广告,代码如下:

屏幕快照 2017-04-12 上午10.27.31.png 屏幕快照 2017-04-12 上午10.27.47.png 屏幕快照 2017-04-12 上午10.28.04.png 屏幕快照 2017-04-12 上午10.28.14.png

效果:

20151217004106417.png
上一篇 下一篇

猜你喜欢

热点阅读