TL;DR

  • 使用的技术: Compositional layout + Diffable data source。iOS 14+。
  • 创建 layout 以描述布局;
  • 创建 dataSource 以提供数据和 view:
    • 使用 CellRegistration 和 dequeueConfiguredReusableCell 来获取 cell;
    • 使用 SupplementaryRegistration 和 dequeueConfiguredReusableSupplementary 来获取 header、footer 等 supplementary views。

Compositional Layout

如上图所示,一个 compositional layout 由若干个 section 组成,每个 section 又由若干个 group 组成,每个 group 又包含若干个 item,因此,创建一个 layout 的过程即先创建最小展示单元 item 开始,再创建 group,创建 section,创建 layout:

func createBasicListLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(44)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: groupSize,
subitems: [item]
) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}

SectionProvider

如果需要多个布局不同的 sections,可以用下面的构造函数来创建 layout:

// UICollectionViewCompositionalLayout
init(
sectionProvider: @escaping UICollectionViewCompositionalLayoutSectionProvider,
configuration: UICollectionViewCompositionalLayoutConfiguration
)

其中闭包 sectionProvider 用于创建并返回 layout 的各个 secitons,声明如下:

typealias UICollectionViewCompositionalLayoutSectionProvider = (Int, NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection?
// arguments meaning: { sectionIndex, layoutEnvironment in ... }

该闭包也会在一些系统事件触发时被调用,如横竖屏切换、系统字体变更、iPad multitasking 引发的 size class 变更等,可以访问 layoutEnvironment 来获取相关信息,以适配这些场景。

LayoutConfiguration

UICollectionViewCompositionalLayoutConfiguration

  • scrollDirection: UICollectionView.ScrollDirection

    • 滚动方向:.vertical | .horizontal
  • interSectionSpacing: CGFloat
    • Sections 之间的间距
  • contentInsetsReference: UIContentInsetsReference
    • 定义 content inset 时的参考边界
    • .automatic | .none | .safeArea | .layoutMargins | .readableContent
      • 红色为 safeArea,绿色为 layoutMargins,蓝色为 readableContent
  • boundarySupplementaryItems: [NSCollectionLayoutBoundarySupplementaryItem]
    • 在整个 layout 边界处的一些附加 items,如全局 header、全局 footer、badge 等

LayoutEnvironment

包含 layout container 和 environment traits 的信息

  • container: NSCollectionLayoutContainer

    • contentSize: CGSize
    • effectiveContentSize: CGSize:content insets 生效之后的 size
    • contentInsets: NSDirectionalEdgeInsets
    • effectiveContentInsets: NSDirectionalEdgeInsets
  • traitCollection: UITraitCollection

List layout

Compositional layout 专门提供了一个接口来创建 list layout:

static func list(using: UICollectionLayoutListConfiguration) -> UICollectionViewCompositionalLayout

UICollectionLayoutListConfiguration 用于配置 list layout 的一些属性,构造函数中需要指定一个 appearance,如 .plain.sidebar.grouped 等。参见 Apple 文档 来查看可配置的属性,下面列出几种。

  • headerMode

    • .none:不展示 header;
    • .supplementary:使用 supplementary views 来展示 headers;
    • .firstItemInSection:使用 section 中的第一个 item 来作为 header。

Cell view 和 supplementary view 的获取

创建 dataSource 的时候,需要传入一个 cellProvider 来提供 cell view:

dataSource = UICollectionViewDiffableDataSource<Int, UUID>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, itemIdentifier: UUID) -> UICollectionViewCell? in
// Configure and return cell.
}

之前我们需要调用 register 方法来注册所需要的 cell 类,然后在 cellProvider 中调用 dequeueReusableCell 方法来获取复用的 cell。iOS 14 提供了一组新的方法,通过 CellRegistration 来配置 cell,然后使用 dequeueConfiguredReusableCell 方法来获取复用的 cell,在调用该方法的时候会自动将 cell 注册到 collectionView 上。如:

let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Int> { cell, indexPath, item in
var contentConfiguration = cell.defaultContentConfiguration() contentConfiguration.text = "\(item)"
contentConfiguration.textProperties.color = .lightGray cell.contentConfiguration = contentConfiguration
} dataSource = UICollectionViewDiffableDataSource<Section, Int>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, itemIdentifier: Int) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: cellRegistration,
for: indexPath,
item: itemIdentifier)
}

注意不要在 cellProvider 里面创建 cell registration,会造成 cell 无法复用,且在 iOS 15+ 上直接报异常

对 cell 的配置通过 UIListContentConfiguration 来完成,调用 cell 的 defaultContentConfiguration 来获取一个包含一些预设属性的 configuration,根据传入的数据对其进行配置,然后再赋值回 cell 的 contentConfiguration。设置 contentConfiguration 会替换掉 cell 现有的 contentView。Cell configuration 具体可参见 Modern cell configuration (WWDC20 10027)

Header、footer 等 supplementary views 的配置和 cell 类似,设置 dataSource 的 supplementaryViewProvider 属性来提供用于创建 view 的闭包,在闭包里面调用 dequeueConfiguredReusableSupplementary 来获取一个复用的 view,该方法接受一个闭包参数 SupplementaryRegistration 来配置 view。

References

iOS Modern Collection View的更多相关文章

  1. Collection View Programming Guide for iOS---(一)----About iOS Collection Views

    Next About iOS Collection Views 关于iOS Collection Views A collection view is a way to present an orde ...

  2. IOS UIView 03- 自定义 Collection View 布局

    注:本人是翻译过来,并且加上本人的一点见解. 前言 UICollectionView 在 iOS6 中第一次被引入,也是 UIKit 视图类中的一颗新星.它和 UITableView 共享一套 API ...

  3. iOS系列译文:自定义Collection View布局

    原文出处: Ole Begemann   译文出处: 黄爱武(@answer-huang).欢迎加入技术翻译小组. UICollectionView在iOS6中第一次被介绍,也是UIKit视图类中的一 ...

  4. Collection View Programming Guide for iOS---(七)---Custom Layouts: A Worked Example

    Custom Layouts: A Worked Example Creating a custom collection view layout is simple with straightfor ...

  5. Collection View Programming Guide for iOS---(五)---Incorporating Gesture Support

      Incorporating Gesture Support 结合手势支持 You can add greater interactivity to your collection views th ...

  6. Collection View Programming Guide for iOS---(三)---Designing Your Data Source and Delegate

      Designing Your Data Source and Delegate 设计你的数据源和委托 Every collection view must have a data source o ...

  7. Collection View 自定义布局(custom flow layout)

    Collection view自定义布局 一般我们自定义布局都会新建一个类,继承自UICollectionViewFlowLayout,然后重写几个方法: prepareLayout():当准备开始布 ...

  8. iOS—使用picker View

    iOS—使用picker View 一.实现效果 说明:点击随机按钮,能够自动选取,下方数据自动刷新. 二.实现思路 1.picker view的有默认高度为162,不可修改. 2.显示数据,需要设置 ...

  9. 自定义 Collection View 布局

    自定义 Collection View 布局 answer-huang 29 Mar 2014 分享文章 UICollectionView 在 iOS6 中第一次被引入,也是 UIKit 视图类中的一 ...

  10. Collection View Programming Guide for iOS---(六)---Creating Custom Layouts

    Creating Custom Layouts 创建自定义布局 Before you start building custom layouts, consider whether doing so ...

随机推荐

  1. NC21467 [NOIP2018]货币系统

    题目链接 题目 题目描述 在网友的国度中共有n种不同面额的货币,第i种货币的面额为a[i],你可以假设每一种货币都有无穷多张.为了方便,我们把货币种数为n.面额数组为a[1..n]的货币系统记作(n, ...

  2. SSD寻址单元IU对寿命的影响——古猫先生存储随笔转载

    SSD寻址单元IU对寿命的影响有多大? 原创 古猫先生 存储随笔 2024-01-30 08:30 发表于浙江 [转载]SSD寻址单元IU对寿命的影响有多大? (qq.com) 随着存储技术的不断进步 ...

  3. Kafdrop

    Kafdrop 是一个用于查看 Kafka 主题和浏览消费者组的 Web UI docker run -d --rm -p 9000:9000 \ -e KAFKA_BROKERCONNECT=hos ...

  4. tensorflow中高维数组乘法运算

    1 前言 声明:本博客里的数组乘法运算是指矩阵乘法运算,不是对应元素相乘. 在线性代数或高等代数中,我们学习了矩阵乘法,那么,什么样的高维数组才能相乘?tensorflow 又是如何定义高维数组运算规 ...

  5. Oracle 高水位(HWM: High Water Mark) 说明

    一. 准备知识:ORACLE的逻辑存储管理. ORACLE在逻辑存储上分4个粒度: 表空间, 段, 区 和 块. 1.1 块: 是粒度最小的存储单位,现在标准的块大小是8K,ORACLE每一次I/O操 ...

  6. 高并发时为什么推荐ReentrantLock而不是synchronized

    目录 1.最初的 synchronized 2.synchronized 的优化 3.但是,JAVA的最终答案 JDK 21 LTS 来了 1.最初的 synchronized 它默认对临界资源添加重 ...

  7. BUUCTF [强网杯 2019]随便注 1

    1. 拿到题目,先输入一个1'试一下是否存在注入点 报错 error 1064 : You have an error in your SQL syntax; check the manual tha ...

  8. 【Azure Storage Account Table】询问批量将存储账户中的表嵌入另一个账户中的办法

    问题描述 询问批量将存储账户中的表嵌入另一个账户中的办法? 问题解答 方式一:使用 AzCopy 使用Az copy做表格的导入导出,注意您需要使用Azcopy 7.3版本来实现对Table的操作,可 ...

  9. 【Azure 环境】使用 az ad group create 时候遇见 Insufficient privileges to complete the operation

    问题描述 使用China Azure,通过Azure CLI 创建AAD组报错,提示权限不足 Insufficient privileges to complete the operation # 使 ...

  10. 【Azure 应用服务】App Service For Linux 环境中,如何修改 Nginx 配置中 server_name的默认值 example.com

    问题描述 在App Service for Linux环境中,部署PHP应用,使用Nginx服务器.因为PHP应用中所有静态资源的URL使用的默认域名为 https://example.com:808 ...