Create complex layouts with UICollectionView using compositional layout. With Composure, you do not need to spend time writing boiler plate code or get into the nitty gritty details of Compositional Layouts. A lot of the complexity is handled for you by Composure.
Add Composure to your project via Swift Package Manager.
https://github.com/eclypse-tms/Composure
Simply add the files in the Sources folder into your project.
Create an enum
that defines each section in your CollectionView and make this enum conform to Int
, CaseIterable
, DefinesCompositionalLayout
protocols as shown below:
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)
}
}
}
In your View Controller while configuring your collection view, add this line to auto-generate the layout based on the enum definitions in Step 1:
override func viewDidLoad() {
super.viewDidLoad()
...
collectionView.collectionViewLayout = generateCompositionalLayout(with: MyCustomLayout.allCases)
...
}
The cells in section 1 will be laid out taking up all available space width-wise while adjusting the height assrc="https://raw.github.com/eclypse-tms/Composure/main/ed. The cells in section 2 will be laid out with dynamic width while their height is fixed.
This repository includes an [example prosrc="https://raw.github.com/eclypse-tms/Composure/main/(https://raw.github.com/eclypse-tms/Composure/main/./Example/Example.xcodeproj) where you can see all possible layouts this library supports.
link |
Stars: 10 |
Last commit: 3 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics