Created
March 19, 2019 08:56
-
-
Save celian-m/211d1f3b442134265be6772ffcbd50e7 to your computer and use it in GitHub Desktop.
Left Align cells for UICollection View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout { | |
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { | |
guard let superArray = super.layoutAttributesForElements(in: rect), | |
let attributes = NSArray(array: superArray, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil } | |
var leftMargin = sectionInset.left | |
var maxY: CGFloat = -1.0 | |
attributes.forEach { layoutAttribute in | |
guard layoutAttribute.representedElementCategory == .cell else { | |
return | |
} | |
guard layoutAttribute.indexPath.section == 0 else { | |
return | |
} | |
if layoutAttribute.frame.origin.y >= maxY { | |
leftMargin = sectionInset.left | |
} | |
layoutAttribute.frame.origin.x = leftMargin | |
leftMargin += layoutAttribute.frame.width + ((self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout)?.collectionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAt: 0) ?? 0 ) | |
maxY = max(layoutAttribute.frame.maxY , maxY) | |
} | |
return attributes | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment