空余时间整理了一下瀑布流的代码,今天总结一下,也说一下个人对于写瀑布流的理解。
先说一下大致思路。
一、写瀑布流实际上就是重新定义UICollectionViewLayout
Layout类中,有3个方法是必定会被依次调用:
prepareLayout: 准备所有view的layoutAttribute信息
collectionViewContentSize: 计算contentsize,显然这一步得在prepare之后进行
layoutAttributesForElementsInRect: 返回在可见区域的view的layoutAttribute信息
二、如果需要传入列数、行间距、列间距、离边缘距离的话需要定义属性或者通过代理传值。
以上是简单的思路,下面上代码。
1、新建一个类,继承UICollectionViewLayout.然后定义几个想要自定义的数值。
下面是.h中的代码,有想要自定义的属性和解释

2、我又定义了几个默认值和一些需要的装一些值的数组

同时写了数组的懒加载

3、 重头戏来了下面几个是核心部分了
首先是
- (void)prepareLayout;
这里面我只写了第一区间的cell,各位要是有兴趣可以尝试全部区间的,授人以鱼不如授人以渔嘛


然后就是
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
这里面主要是计算出对应cell的frame,然后返回。计算的方法千变万化,根据需求计算出合理的frame就行,下面是我的一种简单的计算方法

最后就是返回cell属性数组和可见区域的view的layoutAttribute信息


以上只是个人见解,有错误之处还希望指出!
网友评论