Modern Collection Views with Compositional Layout_1
Just a noob try to understand this amazing feature and use it on his project, slap him harder if you saw anything wrong…(or that’s just what you like…)
Here we talk about some basics
Basic
we can configure our layout using a function, for UICollectionViewCompositionalLayout, besides item and section, we now have another stored name call “group”
The overall design is to create item then group → section, and put section in UICollectionViewCompositionalLayout
- NSCollectionLayoutSize → set width/height of item size
- NSCollectionLayoutItem
- NSCollectionLayoutGroup(.horizontal/.vertical)
- NSCollectionLayoutSection
- UICollectionViewCompositionalLayout
- NSDirectionalEdgeInsets → if you want to set inset between item
The tricky part is to set NSCollectionLayoutSize(widthDimension:heightDimension:), will have close look later, just remember the flow first
Groups inside group
there are many layout you can build, like below one, we have 4 items/groups nested inside a large vertical group
- A full width photo.
- A ‘main’ photo with a pair of vertically stacked smaller photos.
- Three smaller photos in a row.
- The reverse of the second style.
A full width photo
➡️ set fullPhotoItem height to be 2/3 of its width
A ‘main’ photo with a pair of vertically stacked smaller photos
⚠️ You may find it easier to start from the outer layer and work backward — bottom to top in the code, because you have to remember that each size is relative to its parent.
🎯 NSCollectionLayoutSize(widthDimension:heightDimension:)
You can set your width/height dimension fix or fractional, so for fractional you need to compare with you parent view, like below mainItem’s parent view is mainWithPairGroup, so if you want it to be 2/3 of its width, you can set .fractionalWidth(2/3), equal height as parent so you then set .fractionalHeight(1)
But if you want to set your image aspect ratio, then you may set your height connect with your width, like mainWithPairGroup, it’s .fractionalWidth(4/9), but you have to calculate the correspond ratio carefully
- 🎯
- mainItem → base the item size you want to create check its parent view(mainWithPairGroup), here you want to make it 2/3 of the width and equal height
- pairItem → it will be put in the trailingGroup which is a vertical group, equal width and 1/2 of its height
- trailingGroup → it will be put in the mainWithPairGroup(horizontal), 1/3 width and same height
- mainWithPairGroup → it should be put with width 1:1, and base on first item(fullPhotoItem) height is 2/3 of its width, mainWithPairGroup’s height should be 4/9 of the width(2/3✖️2/3)
Three smaller photos in a row
➡️ set its height to be 1/3 of fullPhotoItem’s height, that’s 2/9 of its width(2/3✖️1/3)
The reverse of the second style
➡️ create another group which exchange mainItem and trailingGroup
Connect all in one group!
➡️ carefully calculate your .fractionalWidth and put child items in subitems
So that’s some basics!