要运行示例项目,请克隆仓库,并首先从 Example 目录运行 pod install
。
iOS 13.0+
CompositionalLayoutViewController 可以通过 CocoaPods 获得。 要安装它,只需将以下行添加到您的 Podfile 中
pod 'CompositionalLayoutViewController'
声明集合视图需要四个步骤。
首先,为了组合复杂的集合视图部分,您需要实现继承自 CollectionViewSection
的 Section
类。
class TextFormSection: CollectionViewSection {
...
}
其次,实现您的 sections 布局。
func layoutSection(environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection
第三,在 func registerCell(collectionView: UICollectionView)
和 func registerSupplementaryView(collectionView: UICollectionView)
中注册集合视图的 cells 和补充视图。
func registerCell(collectionView: UICollectionView) {
// register cells here
}
func registerSupplementaryView(collectionView: UICollectionView) {
// register supplementary views here
}
请确保您实现了 func supplementaryView(_ collectionView: UICollectionView, kind: String, indexPath: IndexPath) -> UICollectionReusableView?
。 您可能需要从集合视图中取消队列 UICollectionReusableView
。
这些 cells 和补充视图通过以下方法进行配置。
func cell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell?
func configureSupplementaryView(_ view: UICollectionReusableView, indexPath: IndexPath)
您还需要在您的 section 类中声明 var snapshotItems: [AnyHashable]
。 此变量包含每个 cell 的数据。
var snapshotItems: [AnyHashable] {
// return AnyHashable items
}
最后,您可以在 CompositionalLayoutViewController
的子类中声明集合视图 sections,如下所示
sections = [
TextFormSection(
items: [
.init(
initialText: nil,
textForm: .init(
placeholder: "Email",
validationHandler: { text in
guard let text = text else {
return false
}
return text.isValidEmailAddress()
},
validationAppearance: .init(
textColor: .red
)
)
),
.init(
initialText: nil,
textForm: .init(
placeholder: "Password",
isSecureTextEntry: true
)
)
]
),
ButtonSection(
buttonTitle: "Login",
action: .handler({
print("Login button pressed")
})
)
]
reloadSections()
并且不要忘记分配管理 sections 数组的 SectionProvider
。
public protocol SectionProvider: AnyObject {
var sections: [CollectionViewSection] { get }
func section(for sectionIndex: Int) -> CollectionViewSection
}
override func viewDidLoad() {
super.viewDidLoad()
...
provider = // assign your provider e.g. presenter in VIPER
...
}
要处理 cell 的选择,请在 CompositionalLayoutViewController
的子类中覆盖 func didSelectItem(at indexPath: IndexPath)
方法。
请参阅示例代码以了解高级用法。
Akira, akira.matsuda@me.com
CompositionalLayoutViewController 在 MIT 许可证下可用。 有关更多信息,请参见 LICENSE 文件。