I can't manage to get this type of layout:
I can only achieve this when I set size of cells in 'sizeForItemAt' method:
I tried solutions from Apple like UICollectionViewCompositionalLayout and subclassing of UICollectionViewLayout. But the first one don't give the flexibility needed for the device rotation because you have to set exact count of subitems in group. Another issue with UICollectionViewCompositionalLayout is scroll time calculations - it doesn't give the full layout after the screen is displayed. Subclassing of UICollectionViewLayout (https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/layouts/customizing_collection_view_layouts) has terrible performance.
But even with all the shortcomings of the above approaches, I did not get exactly the layout that I need. I can imagine that we can use an additional type of cell that contains a grid of four cells, but it's also not flexible.
I will appreciate any help.


This layout can be done with a custom
UICollectionViewLayoutand is probably much more straight-forward than it might seem.First, think about the layout as a grid for each section... 4-columns x n rows:
Because we're using squares, the first item will take up 2-columns and 2-rows.
To avoid width/height confusion and replication, we'll call the 2x2 item the "Primary" item, and the 1x1 items "Secondary" items.
So, when we calculate the layout rectangles, we can say:
That works fine, giving us this on an iPhone 14 Pro Max:
It's not quite that simple though, because when we rotate the phone, we don't want this:
and if we're on an iPad, we definitely don't want this:
So, we need to decide how wide we can go for that layout.
Current phones range from 275 to 430 points wide (in Portrait orientation), so we might say:
If we decide we want the Primary item to be 200x200, that changes the initial part of our layout code to:
Now if our layout looks like this (again, iPhone 14 Pro Max):
rotating the phone gives us this:
and the iPad looks like this:
We may still want some conditional calculations... that same code on an iPhone SE looks like this:
So, a Primary size of 200x200 might be too big for that device.
Additionally, as you can see, setting an explicit Primary item size won't fill the width exactly. An iPhone SE in Landscape orientation has a view width of 667. If the secondary size (the column width) is 100, 6 columns gets us 600-points, leaving 667-points of empty space on the end.
If that's acceptable, great, less work :) Otherwise, we can do a "best fit" calculation which would either "grow" the size a bit to fill it out, or "shrink" the size a bit and expand to 7 columns.
And... if you want section spacing and/or headers, that would need to be factored in as well.
Here, though, is some sample code to get to this point: