移动端访问不佳,请访问我的个人博客

最近项目中需要用到瀑布流的效果,但是用UICollectionViewFlowLayout又达不到效果,自己动手写了一个瀑布流的layout,下面是我的心路路程

先先上效果图与demo地址

因为是用UICollectionView来实现瀑布流的,决定继承UICollectionViewLayout来自定义一个layout来实现一个简单瀑布流的布局,下面是需要重写的方法:

  • 重写这个属性得出UICollectionView的ContentSize:collectionViewContentSize
  • 重写这个方法来得到每个item的布局:layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
  • 重写这个方法给UICollectionView所有item的布局:layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
  • 重写这个方法来实现UICollectionView前的操作:prepare()

实现思路

通过代理模式获得到需要的列数和每一item的高度,用过列数与列之间的间隔和UICollectionView的宽度来得出每一列的宽度,item从左边到右布局,下一列的item放到高度最小的列下面,防止每列的高度不均匀,下面贴上代码和注释:

import UIKit

@objc protocol WCLWaterFallLayoutDelegate {
    //waterFall的列数
    func columnOfWaterFall(_ collectionView: UICollectionView) -> Int
    //每个item的高度
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForItemAt indexPath: IndexPath) -> CGFloat
}

class WCLWaterFallLayout: UICollectionViewLayout {

    //代理
    weak var delegate: WCLWaterFallLayoutDelegate?
    //行间距
    @IBInspectable var lineSpacing: CGFloat   = 0
    //列间距
    @IBInspectable var columnSpacing: CGFloat = 0
    //section的top
    @IBInspectable var sectionTop: CGFloat    = 0 {
        willSet {
            sectionInsets.top = newValue
        }
    }
    //section的Bottom
    @IBInspectable var sectionBottom: CGFloat  = 0 {
        willSet {
            sectionInsets.bottom = newValue
        }
    }
    //section的left
    @IBInspectable var sectionLeft: CGFloat   = 0 {
        willSet {
            sectionInsets.left = newValue
        }
    }
    //section的right
    @IBInspectable var sectionRight: CGFloat  = 0 {
        willSet {
            sectionInsets.right = newValue
        }
    }
    //section的Insets
    @IBInspectable var sectionInsets: UIEdgeInsets      = UIEdgeInsets.zero
    //每行对应的高度
    private var columnHeights: [Int: CGFloat]                  = [Int: CGFloat]()
    private var attributes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()

    //MARK: Initial Methods
    init(lineSpacing: CGFloat, columnSpacing: CGFloat, sectionInsets: UIEdgeInsets) {
        super.init()
        self.lineSpacing      = lineSpacing
        self.columnSpacing    = columnSpacing
        self.sectionInsets    = sectionInsets
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    //MARK: Public Methods

    //MARK: Override
    override var collectionViewContentSize: CGSize {
        var maxHeight: CGFloat = 0
        for height in columnHeights.values {
            if height > maxHeight {
                maxHeight = height
            }
        }
        return CGSize.init(width: collectionView?.frame.width ?? 0, height: maxHeight + sectionInsets.bottom)
    }

    override func prepare() {
        super.prepare()
        guard collectionView != nil else {
            return
        }
        if let columnCount = delegate?.columnOfWaterFall(collectionView!) {
            for i in 0..<columnCount {
                columnHeights[i] = sectionInsets.top
            }
        }
        let itemCount = collectionView!.numberOfItems(inSection: 0)
        attributes.removeAll()
        for i in 0..<itemCount {
            if let att = layoutAttributesForItem(at: IndexPath.init(row: i, section: 0)) {
                attributes.append(att)
            }
        }
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        if let collectionView = collectionView {
            //根据indexPath获取item的attributes
            let att = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
            //获取collectionView的宽度
            let width = collectionView.frame.width
            if let columnCount = delegate?.columnOfWaterFall(collectionView) {
                guard columnCount > 0 else {
                    return nil
                }
                //item的宽度 = (collectionView的宽度 - 内边距与列间距) / 列数
                let totalWidth  = (width - sectionInsets.left - sectionInsets.right - (CGFloat(columnCount) - 1) * columnSpacing)
                let itemWidth   = totalWidth / CGFloat(columnCount)
                //获取item的高度,由外界计算得到
                let itemHeight  = delegate?.waterFall(collectionView, layout: self, heightForItemAt: indexPath) ?? 0
                //找出最短的那一列
                var minIndex = 0
                for column in columnHeights {
                    if column.value < columnHeights[minIndex] ?? 0 {
                        minIndex = column.key
                    }
                }
                //根据最短列的列数计算item的x值
                let itemX  = sectionInsets.left + (columnSpacing + itemWidth) * CGFloat(minIndex)
                //item的y值 = 最短列的最大y值 + 行间距
                let itemY  = (columnHeights[minIndex] ?? 0) + lineSpacing
                //设置attributes的frame
                att.frame  = CGRect.init(x: itemX, y: itemY, width: itemWidth, height: itemHeight)
                //更新字典中的最大y值
                columnHeights[minIndex] = att.frame.maxY
            }
            return att
        }
        return nil
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attributes
    }
}

最后附带demo地址,大家喜欢的话可以star一下

上面是简单的瀑布流的实现过程,希望大家能学到东西,有很多地方考虑的不足,欢迎大家交流学习,谢谢大家的阅读~~

iOS开发进阶 - 自定义UICollectionViewLayout实现瀑布流布局的更多相关文章

  1. iOS:UICollectionView纯自定义的布局:瀑布流布局

    创建瀑布流有三种方式:   第一种方式:在一个ScrollView里面放入三个单元格高度一样的tableView,禁止tableView滚动,只需让tableView随着ScrollView滚动即可. ...

  2. iOS开发进阶

    <iOS开发进阶>基本信息作者: 唐巧 出版社:电子工业出版社ISBN:9787121247453上架时间:2014-12-26出版日期:2015 年1月开本:16开页码:268版次:1- ...

  3. iOS开发进阶(唐巧)读书笔记(一)

    如何提高iOS开发技能 1.阅读博客:https://github.com/tangqiaoboy/iOSBlogCN 40多位iOS开发博主的博客地址 2.读书:每年阅读一本高质量的iOS开发书籍 ...

  4. iOS开发之自定义表情键盘(组件封装与自动布局)

    下面的东西是编写自定义的表情键盘,话不多说,开门见山吧!下面主要用到的知识有MVC, iOS开发中的自动布局,自定义组件的封装与使用,Block回调,CoreData的使用.有的小伙伴可能会问写一个自 ...

  5. 详解iOS开发之自定义View

    iOS开发之自定义View是本文要将介绍的内容,iOS SDK中的View是UIView,我们可以很方便的自定义一个View.创建一个 Window-based Application程序,在其中添加 ...

  6. Xamarin自定义布局系列——瀑布流布局

    Xamarin.Forms以Xamarin.Android和Xamarin.iOS等为基础,自己实现了一整套比较完整的UI框架,包含了绝大多数常用的控件,如下图 虽然XF(Xamarin.Forms简 ...

  7. 【Swift】IOS开发中自定义转场动画

    在IOS开发中,我们model另外一个控制器的时候,一般都使用默认的转场动画. 其实我们可以自定义一些转场动画.达到不同的转场效果. 步骤如下:(photoBrowser是目标控制器) 1.在源控制器 ...

  8. iOS开发进阶--1.多线程简介

    学习是由已知的知识模型推理未知的知识模型的的过程. 本文适合学习完objective-c基础,想进一步提高做iOS开发的同学阅读. 在说线程的时候,我们先看看进程. 1.进程 每一个运行在系统中的应用 ...

  9. 自定义UICollectionViewLayout 实现瀑布流

    今天研究了一下自定义UICollectionViewLayout. 看了看官方文档,要自定义UICollectionViewLayout,需要创建一个UICollectionViewLayout的子类 ...

随机推荐

  1. Web浏览器导出FTP服务器上的文件

    开发思路:1.代码登录ftp服务器下载文件到服务器2.通过web浏览器下载服务器上的文件 using System; using System.Collections; using System.Co ...

  2. Go语言 map的实现

    Go中的map在底层是用哈希表实现的,你可以在 $GOROOT/src/pkg/runtime/hashmap.goc 找到它的实现. 数据结构 哈希表的数据结构中一些关键的域如下所示: struct ...

  3. linLINUX中常用操作命令

    LINUX中常用操作命令 Linux简介及Ubuntu安装 常见指令 系统管理命令 打包压缩相关命令 关机/重启机器 Linux管道 Linux软件包管理 vim使用 用户及用户组管理 文件权限管理 ...

  4. 2017Summmer_上海金马五校 F题,G题,I题,K题,J题

    以下题目均自己搜 F题  A序列 一开始真的没懂题目什么意思,还以为是要连续的子串,结果发现时序列,简直智障,知道题意之后,好久没搞LIS,有点忘了,复习一波以后,直接双向LIS,处理处两个数组L和R ...

  5. 统计学习方法笔记 -- KNN

    K近邻法(K-nearest neighbor,k-NN),这里只讨论基于knn的分类问题,1968年由Cover和Hart提出,属于判别模型 K近邻法不具有显式的学习过程,算法比较简单,每次分类都是 ...

  6. 【react 分页器】 基于react-virtualized组件的分页器

    react-virtualized 组件本身没有提供分页器功能,见这个issue:https://github.com/bvaughn/react-virtualized/issues/24 如果想给 ...

  7. django中同源策略和跨域解决方案

    一  同源策略 1.1何谓同源? 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源. 举个例子: 下表给出了相对http://a.xyz.com/dir/page.html同 ...

  8. python 面向对象(进阶篇)转载武沛齐

    上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  9. windows 最大支持线程数

    WINDOWS操作系统中可以允许最大的线程数 默认情况下,一个线程的栈要预留1M的内存空间 而一个进程中可用的内存空间只有2G,所以理论上一个进程中最多可以开2048个线程 但是内存当然不可能完全拿来 ...

  10. win下如何解决在chrome的同源访问问题

    引子:本来是想验证如果在网页中包含多个框架,那么就会存在两个以上的不同全局环境,如果从一个框架引用另一个框架的数据比如数组a,那么用 instanceof 判断这个数组a是不是另个框架Array的实例 ...