iOS控件-UICollectionView基本使用详解

来源:互联网 发布:python免费视频教程 编辑:程序博客网 时间:2024/06/04 17:47

与UITableView的初步比较


  • UITableView应该是大家最熟悉的控件了,UICollectionView的使用与之类似,但又有所区别,如下介绍。
    相同点:

    • 1.都是通过datasource和delegate驱动的(datasource和delegate官方文档传送),因此在使用的时候必须实现数据源与代理协议方法;
    • 2.性能上都实现了循环利用的优化。

    不同点

    • 1.UITableView的cell是系统自动布局好的,不需要我们布局。但UICollectionView的cell是需要我们自己布局的。所以我们在创建UICollectionView的时候必须传递一个布局参数,系统提供并实现了一个布局样式:流水布局(UICollectionViewFlowLayout)(流水布局官方文档传送)。
      • 注:苹果关于FlowLayout的解析
    • 2.UITableViewController的self.view == self.tableview;,但UICollectionViewController的self.view != self.collectionView;
    • 3.UITableView的滚动方式只能是垂直方向, UICollectionView既可以垂直滚动,也可以水平滚动;
    • 4.UICollectionView的cell只能通过注册来确定重用标识符。

    结论: 换句话说,UITableView的布局是UICollectionView的flow layout布局的一种特殊情况,类比于同矩形与正方形的关系

下面简单介绍几个基本用法(难度从低到高)


1. UICollectionView普通用法(FlowLayout布局)

  • 上面我们提到了UICollectionView与UITableView的用法非常类似,下面就让我们完全根据创建UITableView的方式来创建一个UICollectionView(请读者类比UITableView的创建方式,实现数据源,代理等,这里就只提到与之不同的方面,详细代码可参考示例Demo)
  • 报错了,提示缺少布局参数,如下:

    缺少布局参数报错示意图
  • 解决报错,我们可以传FlowLayout参数方式,也可以重写内部init方法。我们这里采用重写init方法,传递布局参数。这样更加体现了封装的思想,把传递布局参数封装在CYXNormalCollectionViewController内,对外只提供统一的外部方法:init方法,代码如下:
    - (instancetype)init{  // 设置流水布局  UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];  // UICollectionViewFlowLayout流水布局的内部成员属性有以下:  /**   @property (nonatomic) CGFloat minimumLineSpacing;   @property (nonatomic) CGFloat minimumInteritemSpacing;   @property (nonatomic) CGSize itemSize;   @property (nonatomic) CGSize estimatedItemSize NS_AVAILABLE_IOS(8_0); // defaults to CGSizeZero - setting a non-zero size enables cells that self-size via -preferredLayoutAttributesFittingAttributes:   @property (nonatomic) UICollectionViewScrollDirection scrollDirection; // default is UICollectionViewScrollDirectionVertical   @property (nonatomic) CGSize headerReferenceSize;   @property (nonatomic) CGSize footerReferenceSize;   @property (nonatomic) UIEdgeInsets sectionInset;   */  // 定义大小  layout.itemSize = CGSizeMake(100, 100);  // 设置最小行间距  layout.minimumLineSpacing = 2;  // 设置垂直间距  layout.minimumInteritemSpacing = 2;  // 设置滚动方向(默认垂直滚动)  layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;  return [self initWithCollectionViewLayout:layout];}
  • 这里我们使用xib自定义cell,通过xib注册cell的代码如下
    // 通过xib注册[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CYXNormalCell class]) bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
  • 初步效果图如下(这里就不详细实现了,剩下请读者参考UITableView的用法(请点这里))

    初步效果图

2. 新手引导页制作

  • 简述
    • 新手引导页,几乎是每个应用都有的,目的为了告诉用户应用的亮点,达到吸引用户的作用。
    • 利用UICollectionView的优势(循环利用)实现新手引导页,既简单又高效,何乐而不为呢。
  • 实现思路:
    • 1.把UICollectionView的每个cell的尺寸设置为跟屏幕一样大;
      layout.itemSize = [UIScreen mainScreen].bounds.size;
    • 2.设置为水平滚动方向,设置水平间距为0.
      // 设置间距layout.minimumLineSpacing = 0;layout.minimumInteritemSpacing = 0;// 设置滚动方向(默认垂直滚动)layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    • 3.开启分页滚动模式
      // 开启分页self.collectionView.pagingEnabled = YES;// 隐藏水平滚动条self.collectionView.showsHorizontalScrollIndicator = NO;// 取消弹簧效果self.collectionView.bounces = NO;
  • 以下是效果图:

    新手引导页
  • 实现详细步骤请参考示例代码:https://github.com/CYXiang/CYXTenMinDemo

3. 图片循环轮播器

  • 请参考我之前的文章(内附代码)《iOS上机题(附个人见解)》

4. 带特效的图片浏览器(自定义布局/上)

以下内容分为两小节:
1> Github例子分析
2> 自己实现一个小Demo

(1)Github例子分析
  • 我们经常在Github上看到一些关于CollectionView的cell切换的炫酷效果,下面我们来分析一下Github上的这个卡片切换带3D动画Demo(RGCardViewLayout)<地址请点>
  • 下面是效果图

    Github上的自定义布局Demo效果图
  • 目录结构分析:目录结构一目了然,关键在于有一个自动布局类(如图所示),这个类继承自UICollectionViewFlowLayout(我们可以猜到他使用的是默认的流水布局),并重写了- (void)prepareLayout- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect等方法。我们试着把这个类里面的重载方法都注释掉,得到的效果跟普通用法的效果一样(这里就不截图了)。由此可见,作者肯定在这些方法内做了个性化的设置。

    目录
  • 关键源码分析:

    • 首先我们看到,作者在- (void)prepareLayout方法内做了对collectionView的初始化布局操作。因此我们可以断定重写此方法是用做初始化的(读者可以尝试修改,改变效果)。
      - (void)prepareLayout  {     [super prepareLayout];     [self setupLayout]; // 初始化布局  }  - (void)setupLayout  {      CGFloat inset  = self.collectionView.bounds.size.width * (6/64.0f);      inset = floor(inset);      self.itemSize = CGSizeMake(self.collectionView.bounds.size.width - (2 *inset), self.collectionView.bounds.size.height * 3/4);      self.sectionInset = UIEdgeInsetsMake(0,inset, 0,inset);      self.scrollDirection = UICollectionViewScrollDirectionHorizontal;  }
    • 接着这个- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect方法应该是最重要的了,同理,我们先注释掉里面个性化的设置,只留[super layoutAttributesForElementsInRect:rect],我们发现炫酷的3D效果没有了。因此可以断定此方法是给每个Cell做个性化设置的。

      方法解析:
      这个方法的返回值是一个数组(数组里面存放着rect范围内所有元素的布局属性)
      这个方法的返回值决定了rect范围内所有元素的排布方式(frame)
      UICollectionViewLayoutAttributes *attrs;
      1.一个cell对应一个UICollectionViewLayoutAttributes对象
      2.UICollectionViewLayoutAttributes对象决定了cell的frame

    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{  // 获取父类(流水布局)已经计算好的布局,在这个基础上做个性化修改  NSArray *attributes = [super layoutAttributesForElementsInRect:rect];  NSArray *cellIndices = [self.collectionView indexPathsForVisibleItems];  if(cellIndices.count == 0 )  {      return attributes;  }  else if (cellIndices.count == 1)  {      mainIndexPath = cellIndices.firstObject;      movingInIndexPath = nil;  }  else if(cellIndices.count > 1)  {      NSIndexPath *firstIndexPath = cellIndices.firstObject;      if(firstIndexPath == mainIndexPath)      {          movingInIndexPath = cellIndices[1];      }      else      {          movingInIndexPath = cellIndices.firstObject;          mainIndexPath = cellIndices[1];      }  }  difference =  self.collectionView.contentOffset.x - previousOffset;  previousOffset = self.collectionView.contentOffset.x;  // 关键代码:取每一个Cell的布局属性,并添加3D效果  for (UICollectionViewLayoutAttributes *attribute in attributes)  {      [self applyTransformToLayoutAttributes:attribute];  }  return  attributes;}
  • 上面关键方法都已经实现了,但是运行发现并没有我们想要的效果,CollectionViewCell并没有实时发生形变。y因此我们还需要调用以下方法。

    方法解析:
    只要滚动屏幕 就会调用 方法  -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    只要布局页面的属性发生改变 就会重新调用  -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 这个方法

    // indicate that we want to redraw as we scroll- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {  return YES;}
(2)仿写Demo
  • 经过上面对代码的分析,我们可以简单了解到自定义layout布局的基本实现,下面就可以仿写一个简单的Demo了,效果图如下。

    效果图
  • 参考代码如下(详细见Github)
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{    return YES;}- (void)prepareLayout{    [super prepareLayout];    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;    // 设置内边距    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);}- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{    // 获得super已经计算好的布局属性    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];    // 计算collectionView最中心点的x值    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;    // 在原有布局属性的基础上,进行微调    for (UICollectionViewLayoutAttributes *attrs in attributes) {        // cell的中心点x 和 collectionView最中心点的x值 的间距        CGFloat delta = ABS(attrs.center.x - centerX);        // 根据间距值 计算 cell的缩放比例        CGFloat scale = 1.2 - delta / self.collectionView.frame.size.width;        NSLog(@"%f,%f",delta,scale);        // 设置缩放比例        attrs.transform = CGAffineTransformMakeScale(scale, scale);    }    return  attributes;}

5.瀑布流布局(自定义布局/下)

  • 瀑布流布局在很多应用中非常常见,效果图如下:

效果图
实现思路(简化)
  • (1)继承自UICollectionViewLayout
  • (2)几个需要重载的方法:
/* * 初始化 */- (void)prepareLayout;/* * 返回rect中的所有的元素的布局属性 */- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;/* * 返回对应于indexPath的位置的cell的布局属性 */- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath/* * 返回collectionView的内容的尺寸 */- (CGSize)collectionViewContentSize;

关键计算代码如下(详细见Github)

/** * 返回indexPath位置cell对应的布局属性 */- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{    // 创建布局属性    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];    // collectionView的宽度    CGFloat collectionViewW = self.collectionView.frame.size.width;    // 设置布局属性的frame    CGFloat w = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;    CGFloat h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath.item itemWidth:w];    // 找出高度最短的那一列    NSInteger destColumn = 0;    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];    for (NSInteger i = 1; i < self.columnCount; i++) {        // 取得第i列的高度        CGFloat columnHeight = [self.columnHeights[i] doubleValue];        if (minColumnHeight > columnHeight) {            minColumnHeight = columnHeight;            destColumn = i;        }    }    CGFloat x = self.edgeInsets.left + destColumn * (w + self.columnMargin);    CGFloat y = minColumnHeight;    if (y != self.edgeInsets.top) {        y += self.rowMargin;    }    attrs.frame = CGRectMake(x, y, w, h);    // 更新最短那列的高度    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));    // 记录内容的高度    CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];    if (self.contentHeight < columnHeight) {        self.contentHeight = columnHeight;    }    return attrs;}

6. 布局切换

  • 苹果已经为我们想好了布局切换的快捷方式,只需要通过以下方法,即可实现。
- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated; // transition from one layout to another- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);
原创粉丝点击