Created
April 21, 2016 15:46
-
-
Save haldun/9e333942af6dc255b9ad17b049bba414 to your computer and use it in GitHub Desktop.
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 | |
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