使用collectionView实现瀑布流

2016-12-06  本文已影响526人  牧晓逸风

使用collectionView实现瀑布流。

系统默认布局

在使用 collectionView 的时候,系统默认提供了 UICollectionViewFlowLayout 流水布局。

在 ViewController 中以懒加载的方式创建 collectionView ,并设置相关的布局。

/// collection View
fileprivate lazy var collectionView: UICollectionView = {
    // 使用系统默认的布局
    let layout = UICollectionViewFlowLayout()
    // 设置每个 section 的内容的间距
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    // 垂直滚动情况下,表示同一行的两个item之间的间距
    layout.minimumInteritemSpacing = 10
    // 垂直滚动情况下,表示连续行之间的行间距
    layout.minimumLineSpacing = 10

    let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.cyan
    return collectionView
}()

在 viewDidLoad() 方法中添加 collectionView。

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(collectionView)
}

此时运行程序,结果如下,只看到青色的背景颜色,并没有看到其他的什么内容。

如果要显示内容,我们需要实现 collection view 的数据源,在上述的懒加载中设置 collection view 的数据源是 ViewController。

...
// 设置数据源
collectionView.dataSource = self
return collectionView

设置了数据源为控制器之后,控制器就要遵守 UICollectionViewDataSource 协议,并实现必须的数据源方法。

// MARK: - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
    // 返回 item 的个数
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 50
    }

    // 返回要展示的 cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "kContentCellID", for: indexPath)
        cell.backgroundColor = UIColor.red
        return cell
    }
}

在 viewDidLoad() 方法中使用唯一标识对 cell 进行注册。

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(collectionView)
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "kContentCellID")
}

注意,注册用的唯一标识字符串一定要和数据源方法中取出cell用的唯一标识一样。为了安全起见,把这个标识符设置为一个常量,并在注册和获取的地方更新代码写法。

/// cell 唯一标识
private let kContentCellID = "kContentCellID"

class ViewController: UIViewController {
    // ...
}

collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentCellID)

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentCellID, for: indexPath)

运行程序,此时就可以看到系统默认的布局的显示方式

流水布局

如果要实现流水布局,就必须自定义布局。创建 HLWaterfallLayout.swift 文件,定义 HLWaterfallLayout 类,并继承 UICollectionViewFlowLayout

class HLWaterfallLayout: UICollectionViewFlowLayout {
    ...
}

准备布局

重写 prepare() 方法,这个方法告诉 layout 对象更新当前的布局,它的默认实现不执行任何操作。子类可以覆盖它,并使用它来设置数据结构或执行任何初始计算,以便稍后执行布局。

/// 准备布局
    override func prepare() {
        super.prepare()

}

在这个方法设置 collection view 的 item 的一些属性,主要就是设置 item 的frame。而 item 的属性是由 UICollectionViewLayoutAttributes 对象管理的,也就是说每一个 item (cell) 对应着一个 UICollectionViewLayoutAttributes 对象。创建 UICollectionViewLayoutAttributes 对象,并设置该对象的 frame,就是对 cell 进行布局。

// 创建 UICollectionViewLayoutAttributes
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)

需要参数 indexPath, 创建indexPath

// 创建 indexPath
let indexPath = IndexPath(item: i, section: 0)

需要参数 i ,也就是具体到每一个cell的索引,此时需要知道item的个数。

// 获取 cell 的个数
let cellCount = collectionView!.numberOfItems(inSection: 0)
for i in 0..<cellCount {
    // 创建 indexPath
    let indexPath = IndexPath(item: i, section: 0)
    // 创建 UICollectionViewLayoutAttributes
    let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
}

设置 attr 的 frame 属性,frame 属性决定了 cell 的布局方式。

定义变量来记录列数,定义数组来记录每一列的高度。

/// 列数
fileprivate lazy var cols: Int = 3
/// 每一列的高度
fileprivate lazy var cellMaxYs: [CGFloat] = Array(repeating: self.sectionInset.top, count: self.cols)

根据要展示的列数来计算cell的宽度,设置cell的高度为随机值。cell的Y值为列中高度最低的列加上行间距。cell的X值是列中高度最低的列所在的X值。设置frame之后,更新数组中最低高度列的值。

let cellW: CGFloat  = (collectionView!.bounds.size.width - sectionInset.left - sectionInset.right - CGFloat(cols - 1) * minimumInteritemSpacing) / CGFloat(cols)
let cellH: CGFloat = CGFloat(arc4random_uniform(100)) + 50.0
// 找到所有列中的高度最小的Y值
let minMaxY = cellMaxYs.min()!
let minYIndex = cellMaxYs.index(of: minMaxY)!
let cellX: CGFloat = sectionInset.left + (cellW + minimumInteritemSpacing) * CGFloat(minYIndex)
let cellY: CGFloat = minMaxY + minimumLineSpacing
attr.frame = CGRect(x: cellX, y: cellY, width: cellW, height: cellH)
// 更新数组中的目前高度最低的Y值
cellMaxYs[minYIndex] = minMaxY + minimumLineSpacing + cellH

定义数组保存 attr

/// cell 对应的 UICollectionViewLayoutAttributes
fileprivate lazy var layoutAttrs: [UICollectionViewLayoutAttributes] = []

// 保存 attr
layoutAttrs.append(attr)

准备布局的最终代码如下所示

override func prepare() {
    super.prepare()

    let cellW: CGFloat  = (collectionView!.bounds.size.width - sectionInset.left - sectionInset.right - CGFloat(cols - 1) * minimumInteritemSpacing) / CGFloat(cols)

    // 获取 cell 的个数
    let cellCount = collectionView!.numberOfItems(inSection: 0)
    for i in 0..<cellCount {
        // 创建 indexPath
        let indexPath = IndexPath(item: i, section: 0)
        // 创建 UICollectionViewLayoutAttributes
        let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)

        let cellH: CGFloat = CGFloat(arc4random_uniform(100)) + 50.0

        // 找到所有列中的高度最小的Y值
        let minMaxY = cellMaxYs.min()!
        let minYIndex = cellMaxYs.index(of: minMaxY)!
        let cellX: CGFloat = sectionInset.left + (cellW + minimumInteritemSpacing) * CGFloat(minYIndex)
        let cellY: CGFloat = minMaxY + minimumLineSpacing
        attr.frame = CGRect(x: cellX, y: cellY, width: cellW, height: cellH)

        // 保存 attr
        layoutAttrs.append(attr)

        // 更新数组中的目前高度最低的Y值
        cellMaxYs[minYIndex] = minMaxY + minimumLineSpacing + cellH
    }
}

返回所有布局

设置好所有的 UICollectionViewLayoutAttributes 之后,要把布局信息返回给系统,重写 layoutAttributesForElements 方法。

/// 返回所有布局
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    return layoutAttrs
}

设置 contentSize

重写 collectionViewContentSize 属性来设置 collection view 的滚动范围

// 设置 contentSize
override var collectionViewContentSize: CGSize {
    let h = cellMaxYs.max()! + sectionInset.bottom
    return CGSize(width: 0, height: h)
}

使用 HLWaterfallLayout

在 ViewController.swift 中,使用 HLWaterfallLayout 布局。

let layout = HLWaterfallLayout()

运行程序,流水布局已初步完成。

相关代码: HLWaterfall

上一篇 下一篇

猜你喜欢

热点阅读