I think your question header is a bit misleading. You don't need to change the layout for each section. You need to show different layouts depending on section.
To achieve what you want you must subclass UICollectionViewLayout
and then determine the layout depending on section. In your case I suggest you to subclass UICollectionViewFlowLayout
as it takes a lot of heavy lifting.
Section 0 - Section 2
of your sample are easily achievable by using just UICollectionViewDelegateFlowLayout
.
As you have "full width" cells there, than you can determine each cell size and insets using the following methods:
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize
func collectionView(UICollectionView, layout: UICollectionViewLayout, minimumLineSpacingForSectionAt: Int) -> CGFloat
First problem will appear when you will try to build Section 3. For that case I suggest you to search for "Waterfall layout", there are implementations on GitHub. When you will figure out how it works, you should do the following:
- Create
UICollectionView
- Create
UICollectionViewFlowLayout
subclass
- Set your layout subclass as a collection view layout.
- For Sections 0-2 use plain
UICollectionViewFlowLayout
possibilities.
- For Sections like section 4 you should override
func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
and calculate attributes manually.
Sorry, if my answer is too broad.
Here are some useful links: