Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rsaenzi/4686a1c0b7d0e3244c002840ba822752 to your computer and use it in GitHub Desktop.
Save rsaenzi/4686a1c0b7d0e3244c002840ba822752 to your computer and use it in GitHub Desktop.
UICollectionViewFlowLayout that aligns all the UICollectionViewCells to the top-left
//
// 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