[Swift]UICollectionViewCellを上揃え

UICollectionViewCellを上揃え

import UIKit

class TopAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
        var sameYElements:[UICollectionViewLayoutAttributes] = []
        var baseline:CGFloat = -2.0
        var height:CGFloat = 0.0
        var basey:CGFloat = 0.0
        let attributesToReturn:[UICollectionViewLayoutAttributes] = super.layoutAttributesForElementsInRect(rect) as [UICollectionViewLayoutAttributes]
        for attributes in attributesToReturn {
            if attributes.representedElementCategory == UICollectionElementCategory.Cell {
                let centerY:CGFloat = CGRectGetMidY(attributes.frame)
                if 1.0 < fabs(centerY - baseline) {
                    baseline = centerY
                    self.__alignTopWithElements(sameYElements, basey:basey)
                    sameYElements.removeAll()
                    height = 0.0
                    basey = 0.0
                }
                sameYElements.append(attributes)
                if height < attributes.frame.size.height {
                    height = attributes.frame.size.height
                    basey = attributes.frame.origin.y
                }
            }
        }
        self.__alignTopWithElements(sameYElements, basey:basey)
        return attributesToReturn
    }
    private func __alignTopWithElements(elements:[UICollectionViewLayoutAttributes], basey:CGFloat) {
        if elements.count < 1 {
            return
        }
        for attributes in elements {
            var rect:CGRect = attributes.frame
            rect.origin.y = basey
            attributes.frame = rect
        }
    }
}