iOS动画相关iOS 开发随笔tableview&&

iOS CollectionView FlowLayout与风火

2016-03-13  本文已影响3260人  linwkr

一般来说,UITableVIew 与 UICollectionView 是iOS开发最重要的两个视图,现在市面上大量的App的布局都可以用这两者实现。

大多数初学者(新入行,包括我自己)可能对 UITableVIew 比较熟悉,而对 UICollectionVIew 了解的比较少,自己看过的几本iOS初级开发类的书籍,对 UICollectionView 也是一笔带过,而不像对 UITableView 那样介绍代码与View控件间交互流程、每个API的用法。一个偶然的机会,我便拾起了对 UICollectionVIew 的学习。

这里对自己学到的东西(见Demo),从三个方面做一个总结:

CollectionView Demo.gif

UICollectionView的理解

```
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
  -   UICollectionViewDelegate 提供与collectioncell 的 selection 与highlighting 交互

##UICollectionView FlowLayout学习与使用

像 UITableView,使用 UICollectionView FlowLayout 允许你定义多个section,每个section有自己的cell、header、footer(如下图)。

![UICollectionViewFlowLayout布局.png](http:https://img.haomeiwen.com/i223244/6400190b74ad45ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

UICollectionView FlowLayout实现了一种线形布局的方式,如下图所示:
![UICollectionViewFlowLayout 布局方式.png](http:https://img.haomeiwen.com/i223244/d0fe62e10ab45121.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

如上图 UICollectionView 的滑动方向是上下,则每一个section则是从左到右的方式排列,当一行不足以放下一个cell时,这个cell就会放到下一行。

你可以通过 ```minimumLineSpacing``` 与 ```minimumInterItemSpacing``` 或者 UICollectionViewDelegateFlowLayout(其默认为UICollectionViewDelegate是同一个对象)的
不过这两个值都只是参考,实际情况还是需要根据UICollectionView排列情况而定。
-  两个cell间的间距可能会大于实际值
-  如果cell不等大,上下两个item的间距就会不同

![4个cell不足已占满屏幕且放不下第五个](http:https://img.haomeiwen.com/i223244/0cb0d932133f5214.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![cell不等大.png](http:https://img.haomeiwen.com/i223244/1ec55d1f9874ca39.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

以下是实现demo种flow布局的代码:

pragma mark - collection view datasource

pragma mark - uicollectionview flow layout delegate

}


###关于定义UICollectionViewFlowLayout子类
在几种情况下,你可能需要定义UICollectionViewFlowLayout子类,最常见的以下几种:
-  另外增加 supplementary 或者 decoration view
-  对UICollectionViewFlowLayout返回的每个cell的frame做改变

比如说可以重载
方法对UICollectionViewFlowLayout计算出的默认位置,做出调整。如把第一个cell下移450个点

![自定义FlowLayout子类.png](http:https://img.haomeiwen.com/i223244/d7c5bad51c1c2ba2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

上一篇下一篇

猜你喜欢

热点阅读