Last active
December 14, 2018 02:47
-
-
Save victorchee/ab4f234b32c973abd34045237395817d to your computer and use it in GitHub Desktop.
Left aligned flow layout for UICollectionView.
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 LeftAlignedFlowLayout: UICollectionViewFlowLayout { | |
| override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { | |
| let attributes = super.layoutAttributesForElements(in: rect) | |
| if let attributes = attributes { | |
| var previousItemFrame = CGRect.zero | |
| for attribute in attributes { | |
| if attribute.representedElementKind == UICollectionView.elementKindSectionFooter || attribute.representedElementKind == UICollectionView.elementKindSectionHeader { | |
| continue | |
| } | |
| var sectionInset = self.sectionInset | |
| if let delegateFlowLayout = collectionView?.delegate as? UICollectionViewDelegateFlowLayout { | |
| if let inset = delegateFlowLayout.collectionView?(self.collectionView!, layout: self, insetForSectionAt: attribute.indexPath.section) { | |
| sectionInset = inset | |
| } | |
| } | |
| var frame = attribute.frame | |
| if attribute.indexPath.item == 0 { | |
| // 第一个 | |
| frame.origin.x = sectionInset.left | |
| attribute.frame = frame | |
| previousItemFrame = frame | |
| } else { | |
| if previousItemFrame.minY == frame.minY { | |
| // 同一行 | |
| // 同一行下一个紧跟上一个 | |
| frame.origin.x = previousItemFrame.maxX + minimumInteritemSpacing | |
| attribute.frame = frame | |
| previousItemFrame = frame | |
| } else { | |
| // 另一行 | |
| if frame.minX != sectionInset.left { | |
| // 每行第一个要居左 | |
| frame.origin.x = sectionInset.left | |
| attribute.frame = frame | |
| } | |
| previousItemFrame = frame | |
| } | |
| } | |
| } | |
| } | |
| return attributes | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment