概述

UICollectionView是从iOS6开始引入使用的,目前应用非常广泛,很牛逼!老外的博客也是这么说的(传送门)

## 与UITableView的初步比较

  • UITableView应该是大家最熟悉的控件了,UICollectionView的使用与之类似,但又有所区别,如下介绍。
    相同点:
  • 1.都是通过datasource和delegate驱动的(datasource和delegate官方文档传送),因此在使用的时候必须实现数据源与代理协议方法;
  • 2.性能上都实现了循环利用的优化。

不同点

  • 1.UITableView的cell是系统自动布局好的,不需要我们布局。但UICollectionView的cell是需要我们自己布局的。所以我们在创建UICollectionView的时候必须传递一个布局参数,系统提供并实现了一个布局样式:流水布局(UICollectionViewFlowLayout)(流水布局官方文档传送)
  • 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;
  • 以下是效果图:

3. 图片循环轮播器

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

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

(1)Github例子分析
  • 我们经常在Github上看到一些关于CollectionView的cell切换的炫酷效果,下面我们来分析一下Github上的这个卡片切换带3D动画Demo(RGCardViewLayout)<地址请点>
  • 下面是效果图
  • 目录结构分析:目录结构一目了然,关键在于有一个自动布局类(如图所示),这个类继承自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);

UICollectionView基本使用详解(OC)的更多相关文章

  1. iOS开发——UI篇OC篇&UICollectionView详解+实例

    UICollectionView详解+实例 实现步骤: 一.新建两个类 1.继承自UIScrollView的子类,比如HMWaterflowView * 瀑布流显示控件,用来显示所有的瀑布流数据 2. ...

  2. iOS开发——实用技术OC篇&事件处理详解

    事件处理详解 一:事件处理 事件处理常见属性: 事件类型 @property(nonatomic,readonly) UIEventType     type; @property(nonatomic ...

  3. iOS开发——UI篇OC&transform详解

    transframe属性详解 1. transform属性 在OC中,通过transform属性可以修改对象的平移.缩放比例和旋转角度 常用的创建transform结构体方法分两大类 (1) 创建“基 ...

  4. iOS开发——UI篇OC篇&UIStackView详解

    UIStackView详解 一.继承关系.遵守协议.隶属框架及可用平台 UIStackView 类提供了一个高效的接口用于平铺一行或一列的视图组合.Stack视图使你依靠自动布局的能力,创建用户接口使 ...

  5. Cocos 2d-X Lua 游戏添加苹果内购(二) OC和Lua交互代码详解

    这是第二篇 Cocos 2d-X Lua 游戏添加苹果内购(一) 图文详解准备流程 这是前面的第一篇,详细的说明了怎样添加内购项目以及填写银行信息提交以及沙盒测试员的添加使用以及需要我们注意的东西,结 ...

  6. OC中NSLog函数输出格式详解

    OC中NSLog函数输出格式详解 %@ 对象 • %d, %i 整数 • %u 无符整形 • %f 浮点/双字 • %x, %X 二进制整数 • %o 八进制整数 • %zu size_t • %p ...

  7. iOS开发 - OC - block的详解 - 基础篇

    深入理解oc中的block 苹果在Mac OS X10.6 和iOS 4之后引入了block语法.这一举动对于许多OC使用者的编码风格改变很大.就我本人而言,感觉block用起来还是很爽的,但一直以来 ...

  8. iOS开发——控制器OC篇&UINavigationController&UITabBarController详解

    UINavigationController&UITabBarController详解 一:UINavigationController 控制器的属性: UINavigationControl ...

  9. iOS开发——多线程OC篇&多线程详解

    多线程详解 前面介绍了多线程的各种方式及其使用,这里补一点关于多线程的概念及相关技巧与使用,相信前面不懂的地方看了这里之后你就对多线程基本上没有什么问题了! 1——首先ios开发多线程中必须了解的概念 ...

随机推荐

  1. java hascode

    有部分代码如下: Cat cat=new Cat("Kitty",2);system.out.println(cat):问题:输出什么? 调用并执行toString()方法,两种情 ...

  2. Zabbix 3.2.6安装过程

    以3.2.6版本的Zabbix为例展开说明 1.准备Lnmp环境. 本次准备的环境: Linux:2.6.32-642.el6.x86_64 Nginx:1.12.0 Mariadb:10.2.6 P ...

  3. dos命令窗口修改编码,CMD编码修改方法

    dos命令窗口修改编码,CMD编码修改方法 第一步,打开命令窗口有两种方法第一种:可以点击左下角的开始按钮,在运行里面输入CMD,然后敲回车2第二种:组合键WIN+R键,组合键后就会弹出窗口,然后输入 ...

  4. Appcan开发笔记:结合JQuery的$.Deferred()完善批量异步发送

    appcan的 uexXmlHttpMgr.send 或者 appcan.ajax无法同步请求(没有找到这个属性),只能异步,造成循环多次提交时由于延迟或网络堵塞等原因无法同步响应,导致提交顺序混乱, ...

  5. linq中日期格式转换或者比较,程序报错说不支持方法的解决办法

    public void TestMethod1(){using (var _context = new hotelEntities()){var rq = DateTime.Now.Date;var ...

  6. 消息队列NetMQ 原理分析4-Socket、Session、Option和Pipe

    消息队列NetMQ 原理分析4-Socket.Session.Option和Pipe 前言 介绍 目的 Socket 接口实现 内部结构 Session Option Pipe YPipe Msg Y ...

  7. 通过history解决ajax不支持前进/后退/刷新

    前言: 现在前后端基本都是通过ajax实现前后端接口数据的交互,但是,ajax有个小小的劣势,即:不支持浏览器“后退”和“前进“键. 但是,现在我们可以通过H5的histroy属性 解决ajax在交互 ...

  8. Oracle的用户、角色以及权限相关操作

    1.创建用户create user KD identified by 123456;2.授予连接数据库的权限grant connect to KD;3.将Scott用户的emp表授权给KD可以查询gr ...

  9. OpenStack(企业私有云)万里长征第四步——DevStack整体安装规划及使用

    一.前言 前期成功通过DevStack安装OpenStack,现将从机房规划到虚拟机搭建的整个过程总结如下,以供日后查阅或有需之人参考. 二.机房规划 这个整个安装过程的重点,能不能成功就看规划的如何 ...

  10. 學習 DT device tree 以 ST 的開發板 STM32F429i-disc1 為例

    目標 因為對 device tree 不是很熟悉, 所以就將 device tree, 設為學習目標. 啟動 注意, 這篇隨筆的解說都放在最下面,會標 Explanation_XX,只要搜尋 Expl ...