I have a UICollectionView with a flow layout and each cell is a square. How do I determine the spacing between each cells on each row? I can't seem to find the appropriate settings for this. I see there's a min spacing attributes on the nib file for a collection view, but I set this to 0 and the cells doesn't even stick.
Any other idea?
An easy way to left-justify is to modify layoutAttributesForElementsInRect: in your subclass of UICollectionViewFlowLayout:
The swift version of Chris solution.
To use it do the following:
a swift version base on mokagio:https://github.com/fanpyi/UICollectionViewLeftAlignedLayout-Swift
A little bit of maths does the trick more easily. The code wrote by Chris Wagner is horrible because it calls the layout attributes of each previous items. So the more you scroll, the more it's slow...
Just use modulo like this (I'm using my minimumInteritemSpacing value as a max value too):
Update: Swift version of this answer: https://github.com/fanpyi/UICollectionViewLeftAlignedLayout-Swift
Taking @matt's lead I modified his code to insure that items are ALWAYS left aligned. I found that if an item ended up on a line by itself, it would be centered by the flow layout. I made the following changes to address this issue.
This situation would only ever occur if you have cells that vary in width, which could result in a layout like the following. The last line always left aligns due to the behavior of
UICollectionViewFlowLayout
, the issue lies in items that are by themselves in any line but the last one.With @matt's code I was seeing.
In that example we see that cells get centered if they end up on the line by themselves. The code below insures your collection view would look like this.
A cleaner swift version for people interested, based on Chris Wagner's answer: