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. NC15976 小C的周末

    题目链接 题目 题目描述 愉快的周末到了,小C和他的N-1个朋友买了M个游戏,游戏编号从1~M.每个游戏都是多人游戏,他们打算周末一起打游戏. 小C的每个朋友都决定好了要玩哪一款游戏(会有一组人打同一 ...

  2. NC24953 [USACO 2008 Jan G]Cell Phone Network

    题目链接 题目 题目描述 Farmer John has decided to give each of his cows a cell phone in hopes to encourage the ...

  3. STC8A/STC8H通用的最小系统板

    STC8(包括之前的STC15)因为自带晶振, 所以最小电路需要的外围元件几乎为0 -- 手册上画的两个电容不加也没问题, 直接加上5V电源就能跑. 这样只需要用排针把管脚都引出就行了. 唯一不方便的 ...

  4. 【Unity3D】半球卷屏特效

    1 原理 ​ 凸镜贴图 和 渐变凸镜贴图 中介绍了使用 OpenGL 实现凸镜贴图及其原理,通过顶点坐标映射到纹理坐标,并构造三角形网格,构建了真正的三维凸镜模型.本文通过 Shader 实现半球卷屏 ...

  5. Springboot+Freemarker+Boostrap实现用户增删改查实战

    说明 做java web用的2大模板语言分别是:thymeleaf和freemarker,thymeleaf前面已经用了很多了,所以今天用一下这个freemarker. 技术栈 springboot ...

  6. 获取Linux mac地址(centos与ubuntu通用)

    ip -a addr| grep link/ether | awk '{print $2}'| head -n 1 获取Linux mac地址(centos与ubuntu通用)

  7. win32 - 控制台聊天

    仅适用于同一台电脑的两个进程聊天,对于不同电脑之前的聊天需要依靠tcp/ip协议. 两个进程是通过发送WM_COPYDATA 消息来传输字节的. 代码如下: Server.cpp #include & ...

  8. time模块,os操作系统及os模块和shutil模块用法---day16

    1.时间模块 import time time.time() 获取本地时间戳 localtime() 获取本地时间元组,参数是时间戳,默认不写是当前 ***** mktime() 通过时间元组获取时间 ...

  9. 文心一言 VS 讯飞星火 VS chatgpt (203)-- 算法导论15.3 2题

    二.对一个16个元素的数组,画出2.3.1节中MERGE-SORT过程运行的递归调用树.解释备忘技术为什么对MERGE-SORT这种分治算法无效.需要写代码的时候,请用go语言. 文心一言,代码不完整 ...

  10. 安装MySql失败( Microsoft Visual C++ 2013 Runtime 64bit)

    参考资料:下载之家 提示你缺少什么版本就安装什么版本.64位或者32位. 文件下载地址:下载之家 不知道有没有失效,如果失效的话大家直接去下载之家搜索下载.