I'm trying to achieve a UICollectionView layout that works like a flow layout, but can conditionally stack multiple items of the grid into a single cell.
Right now I'm using a helper struct, AssetStack
, to achieve this. Each grid item displays one of these stacks, even if it's just a single item in the stack. The problem is that this makes datasource updates tricky as section counts change, and it mixes a lot of layout logic into the data structure. It also means I can't animate the transition easily.
It seems like a custom flow layout or compositional layout could do this, but I'm not sure how, and rather than spending another month on APIs that don't turn out to do what I need, I thought I'd ask the experts here.
Thanks y'all
There are a lot of unknown parts to this, including ...
13, 14, 16, 17
are all selected, should16
and17
move from section2
to section1
?and so on.
But, let's start with the basics and see if you can go from there.
With a custom
UICollectionViewLayout
, we generate an array of frames for the collection view to use for its cells - much in the way we would define view frames.Creating a custom "grid" (think vertical flow layout) is fairly straightforward (this is not the actual code -- just explaining the logic):
and it looks like this:
Now, suppose we select some cells:
If we want to "collapse" (or "stack") the consecutive selected cells, we can modify our logic slightly by saying:
So, our loop looks like this:
and we get this output:
So, we can define one array of cell frames "un-collapsed" and a second array "collapsed" -- and then tell the collection view update its layout inside an animation block:
In your comments, you want to "fine-tune" the stacking animation... since collection view cells are views we can animated them individually, then generate the new layout and animate the rest of the cells.
Here is a complete example you can play with...
Simple Cell Class
Custom Layout Class
Data Object struct - assuming we'd have complex cells...
Example Controller Class
How it looks when running:
Notes:
Again, a lot of unknowns about your actual goals and implementations -- but this may give you some ideas.