I am using a UICollectionView in my project, where there are multiple cells of differing widths on a line. According to: https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html
it spreads the cells out across the line with equal padding. This happens as expected, except I want to left justify them, and hard code a padding width.
I figure I need to subclass UICollectionViewFlowLayout, however after reading some of the tutorials etc online I just don't seem to get how this works.
In swift. According to Michaels answer
The above code works for me. I would like to share the respective Swift 3.0 code.
Based on answers here, but fixed crashes and aligning problems when your collection view is also got headers or footers. Aligning left only cells:
Thanks for the Michael Sand's answer. I modified it to a solution of multiple rows (the same alignment Top y of each row) that is Left Alignment, even spacing to each item.
Building on Michael Sand's answer, I created a subclassed
UICollectionViewFlowLayout
library to do left, right, or full (basically the default) horizontal justification—it also lets you set the absolute distance between each cell. I plan on adding horizontal center justification and vertical justification to it, too.https://github.com/eroth/ERJustifiedFlowLayout
With Swift 4.1 and iOS 11, according to your needs, you may choose one of the 2 following complete implementations in order to fix your problem.
#1. Left align autoresizing
UICollectionViewCell
sThe implementation below shows how to use
UICollectionViewLayout
'slayoutAttributesForElements(in:)
,UICollectionViewFlowLayout
'sestimatedItemSize
andUILabel
'spreferredMaxLayoutWidth
in order to left align autoresizing cells in aUICollectionView
:CollectionViewController.swift
FlowLayout.swift
CollectionViewCell.swift
Expected result:
#2. Left align
UICollectionViewCell
s with fixed sizeThe implementation below shows how to use
UICollectionViewLayout
'slayoutAttributesForElements(in:)
andUICollectionViewFlowLayout
'sitemSize
in order to left align cells with predefined size in aUICollectionView
:CollectionViewController.swift
FlowLayout.swift
CollectionViewCell.swift
Expected result: