Search code examples
iosasyncdisplaykit

Replace/update layout in ASCollectionNode


I'm trying to switch layouts in a ASCollectionNode. When using standard UICollectionView you can call

self.collectionView.setCollectionViewLayout(layout, animated: true)

to replace/update existing layout.

This, however, doesn't work with ASCollectionNode. Calling

self.collectionView.view.setCollectionViewLayout(layout, animated: true)

does nothing. How would one achieve such functionality?


Solution

  • So, what one needs to do to achieve the described functionality, is to get rid of all UICollectionViewLayout subclasses and leave only 1 instance of base UICollectionViewLayout. Then, override layoutSpecThatFits method inside ASCellNode subclass and return a layout specs based of some flag, enumeration or any other mechanism one sees fit to choose between collection display modes. This is essentially a replacement for the several layout mechanism used for default collection views. Then, implement a ASCollectionViewLayoutInspecting protocol with collectionView:constrainedSizeForNodeAt: method (in view controller, most likely), return ASSizeRange's appropriate for each display mode. At last, call relayoutItems method on your ASCollectionNode instance to kickoff the layout recalculation. Wrap it in UIView animation block, if needed.

    P.S. I think it's worth mentioning that if in collectionView:constrainedSizeForNodeAt: you return the same range value for each display mode (maybe you only want to change layout spec inside the cells, but not their actual size), then relayoutItems will not do anything, basically. ASDK will use the cached layout, because it will consider it valid based on the fact that size range value didn't change. You may need to come up with some layout invalidation strategy to make relayoutItems work is such scenario.