Created
March 5, 2021 03:14
-
-
Save rsaenzi/4686a1c0b7d0e3244c002840ba822752 to your computer and use it in GitHub Desktop.
UICollectionViewFlowLayout that aligns all the UICollectionViewCells to the top-left
This file contains 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
// | |
// UICollectionViewLeftAlignmentFlowLayout.swift | |
// | |
// Created by Rigoberto Sáenz Imbacuán (https://www.linkedin.com/in/rsaenzi/) | |
// Copyright © 2021. All rights reserved. | |
// | |
class UICollectionViewLeftAlignmentFlowLayout: UICollectionViewFlowLayout { | |
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { | |
let allCells = super.layoutAttributesForElements(in: rect) | |
// This locator is used to calculate the position of each cell | |
var locator = CGPoint.zero | |
allCells?.forEach { cell in | |
// Determine if the locator should be located in a new row | |
if (locator.x + cell.frame.width) > rect.width, cell.indexPath.row > 0 { | |
locator.x = 0 | |
locator.y += cell.frame.height + minimumLineSpacing | |
} | |
// Cell is positioned where the locator is | |
cell.frame.origin = locator | |
// Move the locator right next to the previous cell | |
locator.x += cell.frame.width + minimumInteritemSpacing | |
} | |
return allCells | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment