当前位置: 首页 > 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.dtcms.com/a/340510.html

相关文章:

  • 氯化钇:科技与高性能材料的核心元素
  • C++高频知识点(三十)
  • 嵌入式音频开发(3)- AudioService核心功能
  • 机器学习数学基础与商业实践指南:从统计显著性到预测能力的认知升级
  • Node.js中的Prisma应用:现代数据库开发的最佳实践
  • 河南萌新联赛2025第六场 - 郑州大学
  • Java:将视频上传到腾讯云并通过腾讯云点播播放
  • 【Task02】:四步构建简单rag(第一章3节)
  • 第三阶段数据-4:SqlHelper类,数据库删除,DataTable创建
  • 【考研408数据结构-08】 图论基础:存储结构与遍历算法
  • Opencv模板匹配
  • 27.语言模型
  • Java + 工业物联网 / 智慧楼宇 面试问答模板
  • C#APP.Config配置文件解析
  • 案例分享:BRAV-7123助力家用型人形机器人,智能生活未来已来
  • 项目各功能介绍
  • 今天我们学习计算机网络技术的虚拟局域网VLAN以及了解三层交换机的概念
  • 应用在运行时,向用户索取(相机、存储)等权限,未同步告知权限申请的使用目的,不符合相关法律法规要求--教你如何解决华为市场上架难题
  • leetcode 1277. 统计全为 1 的正方形子矩阵 中等
  • (nice!!!)(LeetCode 每日一题) 1277. 统计全为 1 的正方形子矩阵 (动态规划)
  • Tumblr长文运营:亚矩阵云手机助力多账号轮询与关键词布局系统
  • 亚矩阵:跨境卖家 YouTube 私域矩阵搭建的高效解决方案
  • JavaScript 性能优化实战:从原理到落地的完整指南
  • AI硬件 - 华为显卡的演进
  • 深入理解MySQL Ⅳ -- SQL性能分析工具
  • 力扣48:旋转矩阵
  • [TryHackMe]Mr Robot CTF(hydra爆破+Wordpress更改主题)
  • IPSec安全概述
  • 医疗AI与医院数据仓库的智能化升级:异构采集、精准评估与高效交互的融合方向(上)
  • 信创产品TongLinkQ安装及springboot2整合使用