Composure
使用组合布局通过 UICollectionView 创建复杂的布局。使用 Composure,您无需花费时间编写样板代码或深入了解组合布局的细节。大部分复杂性都由 Composure 处理。
轻松创建类似布局
安装(iOS,macCatalyst)
Swift PM
通过 Swift Package Manager 将 Composure 添加到您的项目中。
https://github.com/eclypse-tms/Composure
用户手册
将 "资源" 文件夹中的文件添加到您的项目中。
使用说明
步骤 1
在您的 Collection View 中创建一个 enum
来定义每个部分,并使这个 enum 遵循 Int
、CaseIterable
和 DefinesCompositionalLayout
协议,如下所示
import UIKit
import Composure
// The enum must be an Int type. Each case in this enum also defines
// the presentation order of those sections in your collection view.
enum MyCustomLayout: Int, CaseIterable, DefinesCompositionalLayout {
case section1
case section2
/// REQUIRED:
func layoutInfo(using layoutEnvironment: NSCollectionLayoutEnvironment) -> CompositionalLayoutOption {
switch self {
// cells in this section take up the available width but their height is unknown
case .section1:
return .fullWidthDynamicHeight(estimatedHeight: 75)
// cells in this section have a fixed height but their width changes depending on the contents
case .section2:
return .dynamicWidthFixedHeight(estimatedWidth: 150, fixedHeight: 150)
}
}
/// OPTIONAL: Only needed if you have header or footer views for each section
func headerInfo(using layoutEnvironment: NSCollectionLayoutEnvironment) -> CompositionalLayoutOption? {
switch self {
case .section1:
return .fullWidthFixedHeight(fixedHeight: 30)
case .section2:
return .fullWidthFixedHeight(fixedHeight: 55)
}
}
}
步骤 2
在您的视图控制器中配置 Collection View 时,添加以下行来自动从步骤 1 中的 enum 定义生成布局
override func viewDidLoad() {
super.viewDidLoad()
...
collectionView.collectionViewLayout = generateCompositionalLayout(with: MyCustomLayout.allCases)
...
}
结果
第1节中的单元格将按照所需宽度填充所有可用空间,并调整高度。第2节中的单元格将具有动态宽度,但高度固定。
所有布局选项
此存储库包含一个示例项目,在其中您可以查看此库支持的所有可能的布局。
设计选择
- 专为与纵向滚动视图一起使用而设计,因为大多数表单也都是这样布局的。
- 视图中每个部分都包含单一类型的布局。尽管在组合布局中可以在同一部分中混合不同类型的布局,但此库设计用于每个部分只能接受一种布局。
- 每个集合布局组占据整个可用宽度。如果您不熟悉“布局组”,可以在苹果的网站上找到布局组的示意图。
- 支持UICollectionView.elementKindSectionHeader和UICollectionView.elementKindSectionFooter类型的标题和页脚视图。
假设
- 与此库一起使用的单元格、标题或页脚视图必须明确约束。约束不足或不正确约束的单元格将无法工作。
- 每个部分中每个单元格周围的一致间距。
更多信息
- 还有其他布局选项,详细信息请参阅这篇 Medium 博文。
- 我们鼓励您运行包含的示例项目,选择一个 iPad 或 iOS 设备,以查看不同布局的细则。