全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

iOS自定义UICollectionViewLayout实现瀑布流布局

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

最近项目中需要用到瀑布流的效果,但是用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瀑布流布局  # iOS瀑布流布局  # iOS瀑布流  # iOS UICollectionView刷新时闪屏的解决方法  # iOS 通过collectionView实现照片删除功能  # iOS中关于Swift UICollectionView横向分页的问题  # 使用iOS控件UICollectionView生成可拖动的桌面的实例  # IOS collectionViewCell防止复用的两种方法  # iOScollectionView广告无限滚动实例(Swift实现)  # iOS自定义collectionView实现毛玻璃效果  # IOS简单实现瀑布流UICollectionView  # ios的collection控件的自定义布局实现与设计  # 重写  # 最短  # 来实现  # 行间  # 有很多  # 写了  # 欢迎大家  # 用过  # 谢谢大家  # 达不到  # 贴上  # 方法来  # 自己动手  # 希望大家能  # 不均匀  # 博客  # pre  # itemWidth  # itemHeight  # cpp 


相关文章: 模具网站制作流程,如何找模具客户?  Python lxml的etree和ElementTree有什么区别  网站制作的步骤包括,正确网址格式怎么写?  如何在云主机快速搭建网站站点?  大学网站设计制作软件有哪些,如何将网站制作成自己app?  黑客入侵网站服务器的常见手法有哪些?  建站主机与服务器功能差异如何区分?  建站之星代理商如何保障技术支持与售后服务?  如何快速查询域名建站关键信息?  logo在线制作免费网站在线制作好吗,DW网页制作时,如何在网页标题前加上logo?  c# 服务器GC和工作站GC的区别和设置  建站主机数据库如何配置才能提升网站性能?  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  最好的网站制作公司,网购哪个网站口碑最好,推荐几个?谢谢?  建站主机与虚拟主机有何区别?如何选择最优方案?  如何快速配置高效服务器建站软件?  网站制作培训多少钱一个月,网站优化seo培训课程有哪些?  如何在阿里云通过域名搭建网站?  临沂网站制作企业,临沂第三中学官方网站?  公司网站制作需要多少钱,找人做公司网站需要多少钱?  php json中文编码为null的解决办法  如何在阿里云虚拟服务器快速搭建网站?  矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?  无锡制作网站公司有哪些,无锡优八网络科技有限公司介绍?  建站之星如何防范黑客攻击与数据泄露?  定制建站流程解析:需求评估与SEO优化功能开发指南  Avalonia如何实现跨窗口通信 Avalonia窗口间数据传递  如何设计高效校园网站?  如何基于PHP生成高效IDC网络公司建站源码?  早安海报制作网站推荐大全,企业早安海报怎么每天更换?  如何在Windows 2008云服务器安全搭建网站?  电脑免费海报制作网站推荐,招聘海报哪个网站多?  如何用PHP工具快速搭建高效网站?  小捣蛋自助建站系统:数据分析与安全设置双核驱动网站优化  网站制作难吗安全吗,做一个网站需要多久时间?  北京企业网站设计制作公司,北京铁路集团官方网站?  制作网站公司那家好,网络公司是做什么的?  高防服务器:AI智能防御DDoS攻击与数据安全保障  微网站制作教程,不会写代码,不会编程,怎么样建自己的网站?  如何选择适配移动端的WAP自助建站平台?  ,柠檬视频怎样兑换vip?  简易网站制作视频教程,使用记事本编写一个简单的网页html文件?  网站制作多少钱一个,建一个论坛网站大约需要多少钱?  建站之星在线版空间:自助建站+智能模板一键生成方案  建站之星在线客服如何快速接入解答?  弹幕视频网站制作教程下载,弹幕视频网站是什么意思?  如何在万网自助建站平台快速创建网站?  如何在云主机上快速搭建多站点网站?  企业微网站怎么做,公司网站和公众号有什么区别?  网站企业制作流程,用什么语言做企业网站比较好? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。