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

iOS开发之UICollectionView为什么需要配合UICollectionViewFlowLayout使用

1. UICollectionView 的职责分离

UICollectionView 本质上只是一个容器,用来展示一系列的 cell(单元格)。
它本身 不关心 cell 的摆放方式,只负责:

  • Cell 的复用(避免性能浪费)

  • Cell 的增删改查

  • 滚动与事件处理

👉 那么 Cell 怎么排版Cell 大小是多少? 行间距、列间距、滚动方向是什么?
这些都不是 UICollectionView 的工作,而是交给 布局对象(Layout object)。


2. 为什么要有 UICollectionViewLayout

苹果采用了 策略模式(Strategy Pattern):

  • UICollectionView 负责数据展示和交互。

  • UICollectionViewLayout 负责计算布局。

  • 这样 UICollectionView 就可以灵活切换布局策略,而不用修改控件本身。

例如:

  • 想要网格布局,用 UICollectionViewFlowLayout

  • 想要环形布局,可以自定义 UICollectionViewLayout

  • 想要卡片轮播(类似 App Store),也可以写自定义布局

👉 这样就实现了 UI 展示与布局解耦


3. UICollectionViewFlowLayout 的作用

UICollectionViewFlowLayout 是 Apple 提供的 默认布局方案,大多数场景够用。

它能做的事情包括:

  • 滚动方向(水平 / 垂直)

  • 行间距列间距

  • section 的内边距(sectionInset)

  • item 的大小(固定大小,或通过 delegate 动态设置)

  • header/footer 的大小

举例:

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical   // 垂直滚动
layout.itemSize = CGSize(width: 100, height: 100) // 固定大小
layout.minimumLineSpacing = 10       // 行间距
layout.minimumInteritemSpacing = 5   // 列间距
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

这样,UICollectionView 就知道 如何排列每个 cell


4. 如果没有 FlowLayout 会怎样?

如果 UICollectionView 没有 UICollectionViewLayout,它就不知道怎么摆放 cell
你会看到:

  • cell 无法显示,因为没有布局信息

  • 即使有数据源,collectionView 也无法渲染

所以,UICollectionView 必须绑定一个 Layout 对象
如果你不想用 UICollectionViewFlowLayout,也可以自己写 UICollectionViewLayout 的子类,完全控制 cell 的位置和大小。


5. 灵活性对比

方案适用场景
UICollectionViewFlowLayout普通的网格、列表、瀑布流(稍微改造)
UICollectionViewCompositionalLayout(iOS 13+)复杂布局(比如 App Store、新闻类 App)
自定义 UICollectionViewLayout特殊布局(环形、3D 卡片、CoverFlow 效果)

✅ 总结

  • UICollectionView 是数据容器,负责 cell 管理和交互。

  • UICollectionViewLayout 是策略类,负责计算 cell 的位置和大小。

  • UICollectionViewFlowLayout 是默认布局(网格/列表),所以常常一起使用。

  • 分离布局的好处是:高度解耦、灵活切换、支持自定义

6. 代码示例

import UIKitclass ViewController: UIViewController {private var collectionView: UICollectionView!private var data = Array(1...20).map { "Item \($0)" }override func viewDidLoad() {super.viewDidLoad()//1.创建自定义布局let layout = UICollectionViewFlowLayout()layout.itemSize = CGSize(width: 100, height: 100)layout.minimumLineSpacing = 10layout.minimumInteritemSpacing = 10layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)//2.初始化collectionViewcollectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)collectionView.backgroundColor = .systemGroupedBackgroundcollectionView.dataSource = self;collectionView.delegate = self;collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "cell")view.addSubview(collectionView)}
}extension ViewController: UICollectionViewDataSource {func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {data.count}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCellcell.configure(with: data[indexPath.row])return cell}}extension ViewController: UICollectionViewDelegate {func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {print("Selected: \(data[indexPath.item])")}
}class CustomCell: UICollectionViewCell {private let label = UILabel()override init(frame: CGRect) {super.init(frame: frame)setUI()}required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}private func setUI(){contentView.backgroundColor = .systemBluecontentView.layer.cornerRadius = 10label.textAlignment = .centerlabel.textColor = .whitelabel.font = .boldSystemFont(ofSize: 18)contentView.addSubview(label)label.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)])}func configure(with text: String) {label.text = text}
}

http://www.lryc.cn/news/626526.html

相关文章:

  • 数据结构-有序二叉树
  • 【机器学习深度学习】Ollama、vLLM、LMDeploy对比:选择适合你的 LLM 推理框架
  • HTML应用指南:利用POST请求获取全国刘文祥麻辣烫门店位置信息
  • 学习threejs,打造宇宙星云背景
  • 数据结构 二叉树 二叉树链式结构的实现
  • 大规模IP轮换对网站的影响(服务器压力、风控)
  • 测试环境搭建和部署(在Linux环境下搭建jdk+Tomcat+mysql环境和项目包的部署)
  • 【39】OpenCV C++实战篇——直线拟合、直线测距、平行线段测距;(边缘检测,剔除噪点,轮廓检测,渐进概率霍夫直线)
  • 本地文件上传到gitee仓库的详细步骤
  • Wireshark捕获电脑与路由器通信数据,绘制波形观察
  • C语言第十章内存函数
  • python numpy.random的基础教程(附opencv 图片转数组、数组转图片)
  • Dog Tricks
  • vue3项目,main.ts中设置router,在各个页面上还用引用vue-router吗
  • 性能测试报告深度解析:从冰冷数据到火热洞察
  • Flink学习
  • 详解flink java table api基础(三)
  • 2.3 Flink的核心概念解析
  • 24V降12V电源芯片WD5030,电路设计
  • linux 内核 - 内存管理单元(MMU)与地址翻译(一)
  • Flink Stream API - 顶层Operator接口StreamOperator源码超详细讲解
  • 软件测试中,JMeter 的作用以及优缺点是什么?
  • 【报错】Please do not run this script with sudo bash
  • three.js学习记录(第四节:材质外观)
  • Git 新手完全指南(二):在vscode中使用git
  • 【图像算法 - 19】慧眼识苗:基于深度学习与OpenCV的大棚农作物生长情况智能识别检测系统
  • PostgreSQL 中的金钱计算处理
  • K8S-Secret资源对象
  • 从零开始学AI——13
  • 机器学习(Machine Learning, ML)