当前位置: 首页 > news >正文

ios swift5 collectionView 瀑布流(两列)

文章目录

  • 1.瀑布流
    • 1.1 demo地址
    • 1.2 记得把部署的最低版本由8改成11,13甚至更高。不然编译会报错
  • 2.动态计算图片和文字的高度

1.瀑布流

1.1 demo地址

CollectionViewWaterfallLayout - github

请添加图片描述

1.2 记得把部署的最低版本由8改成11,13甚至更高。不然编译会报错

请添加图片描述

2.动态计算图片和文字的高度

//可以正常使用
import UIKit
import SnapKit
class ConcernedVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {let cellReuseIdentifier = "WaterfallCell"let itemsPerRow: CGFloat = 2let sectionInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)let itemSpacing: CGFloat = 10 // Spacing between items in the same columnvar columnHeights: [CGFloat] = [0, 0] // Heights of the two columnslet sampleData: [(image: UIImage, text: String)] = [(UIImage(named: "img_about us_app")!, "Sample Text 1"),(UIImage(named: "banner")!, "Sample Text 2adfahdfkajdfiahdofhadoifhaodhfaoihdfhasdifhaidhfapfdhiashf"),(UIImage(named: "img_about us_app")!, "Sample Text 1"),(UIImage(named: "banner")!, "Sample Text 2adfahdfkajdfiahdofhadoifhaodhfaoihdfhasdifhaidhfapfdhiashf"),(UIImage(named: "img_about us_app")!, "Sample Text 1"),(UIImage(named: "banner")!, "Sample Text 2adfahdfkajdfiahdofhadoifhaodhfaoihdfhasdifhaidhfapfdhiashf"),(UIImage(named: "img_about us_app")!, "Sample Text 1"),(UIImage(named: "img_about us_app")!, "Sample Text 1"),// Add more sample data here]override func viewDidLoad() {super.viewDidLoad()//        let layout = UICollectionViewFlowLayout() // Create a layout instance
//        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) // Initialize UICollectionView with the layoutcollectionView.delegate = selfcollectionView.dataSource = selfcollectionView.register(WaterfallCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)collectionView.backgroundColor = .white}// MARK: UICollectionViewDataSourceoverride func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return sampleData.count}override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! WaterfallCelllet data = sampleData[indexPath.item]cell.configure(with: data)return cell}// MARK: UICollectionViewDelegateFlowLayoutfunc collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {let paddingSpace = sectionInsets.left * (itemsPerRow + 1)let availableWidth = collectionView.frame.width - paddingSpacelet widthPerItem = availableWidth / itemsPerRowlet data = sampleData[indexPath.item]let imageAspectRatio = data.image.size.width / data.image.size.heightlet textHeight = data.text.height(withConstrainedWidth: widthPerItem - 16, font: UIFont.systemFont(ofSize: 14))let imageHeight = min(200, widthPerItem / imageAspectRatio) // Limit image heightlet totalHeight = imageHeight + textHeight + 16return CGSize(width: widthPerItem, height: totalHeight)}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {return sectionInsets}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {return sectionInsets.left}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {return sectionInsets.left}
}
class WaterfallCell: UICollectionViewCell {let imageView = UIImageView()let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)contentView.backgroundColor = .yellowcontentView.addSubview(imageView)imageView.contentMode = .scaleAspectFillimageView.clipsToBounds = truecontentView.addSubview(label)label.numberOfLines = 2label.font = UIFont.systemFont(ofSize: 14)}required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}func configure(with data: (image: UIImage, text: String)) {imageView.image = data.imagelabel.text = data.textlet imageAspectRatio = data.image.size.width / data.image.size.heightlet imageHeight = frame.width / imageAspectRatioimageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: imageHeight)label.frame = CGRect(x: 0, y: imageHeight + 8, width: frame.width, height: labelHeight)}private var labelHeight: CGFloat {let labelWidth = frame.width - 16return label.text?.height(withConstrainedWidth: labelWidth, font: UIFont.systemFont(ofSize: 14)) ?? 0}
}
extension String {func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)return ceil(boundingBox.height)}
}//使用
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let vc = ConcernedVC(collectionViewLayout: layout)
http://www.lryc.cn/news/128678.html

相关文章:

  • 创建一个简单的HTML Viewer应用程序
  • 无公网IP,公网SSH远程访问家中的树莓派教程
  • 「UG/NX」Block UI 超级截面SuperSection
  • 高层建筑全景vr火灾隐患排查模拟培训软件助力群众防范火灾伤害
  • 【WPF】 本地化的最佳做法
  • VS2017编译同事VS2022创建的库,报错无法运行rc.exe
  • Leetcode49. 字母异位词分组
  • 设计模式之工厂方法模式(FactoryMethod)
  • python的进度条tqdm库,显示时进度条不换行设置
  • spark的使用
  • 力扣:66. 加一(Python3)
  • Go的标准库Context理解
  • Nuxt3_1_路由+页面+组件+资源+样式 使用及实例
  • Kafka第三课
  • elasticsearch修改es集群的索引副本数量
  • 【SpringCloud】Ribbon定制化配置
  • Mac terminal 每次打开都要重新配置文件
  • el-button实现按钮,鼠标移入显示,移出隐藏
  • uniapp+uview封装小程序请求
  • idea常见错误大全之:解决全局搜索失效+搜索条件失效(条件为空)+F8失灵
  • 【论文阅读】基于深度学习的时序预测——LTSF-Linear
  • 02.FFMPEG的安装和添加硬件加速自编译
  • elementUI 的上传组件<el-upload>,自定义上传按钮样式
  • 【卷积神经网络】卷积,池化,全连接
  • 【SA8295P 源码分析】76 - Thermal 功耗 之 /dev/thermalmgr 相关调试命令汇总
  • 以太网(一):PoE供电
  • 骨传导耳机游泳能戴吗?骨传导游泳耳机哪个牌子好?
  • 18万字应急管理局智慧矿山煤矿数字化矿山技术解决方案WORD
  • 【mysql】MySQL CUP过高如何排查?
  • lua实现http的异步回调