Skip to content

Instantly share code, notes, and snippets.

@haldun
Created April 21, 2016 15:46
Show Gist options
  • Save haldun/9e333942af6dc255b9ad17b049bba414 to your computer and use it in GitHub Desktop.
Save haldun/9e333942af6dc255b9ad17b049bba414 to your computer and use it in GitHub Desktop.
import UIKit
final class MasonaryFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
guard let attrs = super.layoutAttributesForItemAtIndexPath(indexPath) else { return nil }
if indexPath.item == 0 {
return attrs
}
if attrs.frame.origin.x - 1 <= sectionInset.left {
return attrs
}
let indexPathForPreviousItem = NSIndexPath(forItem:indexPath.item - 1, inSection:indexPath.section)
guard let layoutAttributesForPreviousItem = layoutAttributesForItemAtIndexPath(indexPathForPreviousItem) else {
return attrs
}
let frameForPreviousItem = layoutAttributesForPreviousItem.frame
let xOffset = frameForPreviousItem.origin.x + frameForPreviousItem.width + minimumInteritemSpacing
guard let newAttrs = attrs.copy() as? UICollectionViewLayoutAttributes else {
return attrs
}
newAttrs.frame.origin.x = xOffset
return newAttrs
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return super.layoutAttributesForElementsInRect(rect)?.flatMap { attr in
if attr.representedElementKind == nil {
return self.layoutAttributesForItemAtIndexPath(attr.indexPath)
}
return attr
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment