I’m not sure if this is a feature or a bug, but when I have two collection views on a view controller using the same instance of UICollectionViewFlowLayout, an interesting thing happens. Note that I’m not using Interface Builder / XIBs for any of this; I’m laying everything out in code.
The first UICollectionView has twelve cells in it, but the second one has 20. When I reload both collection views, both act as if their contentSize property has 20 cells in it. This means that when I scroll to the right of the first UICollectionView and get past the first (and only) 12 cells, my app crashes (because I’m pulling data from an array that only has 12 cells’ worth of data).
To get around this for now, I’m instantiating two identical UICollectionViewFlowLayout objects and assigning each to its own collection view. Is this normal behavior?
I’m only getting started writing code with UICollectionViews, so forgive my ignorance if I’m exuding any!
Don’t do this. A collection view and a layout object should be a 1:1 relationship. The layout object has a property,
collectionView, which obviously can only hold a reference to one collection view.When the collection view then asks the layout for its size and so forth, the layout object is going to base everything on the second collection view you assigned the layout to, since this will be held in the
collectionViewproperty.I couldn’t find an explicit statement in the docs not to share a layout object between collection views, but the property discussed above should make it clear that this is not an intended use.