与Swift的UICollectionViewLayout项间距

时间:2015-07-10 21:32:35

标签: ios swift uicollectionview uicollectionviewlayout

我尝试将this Objective-C的答案转换为Swift,但因为它总是在这行崩溃:

var previousLayoutAttributes: UICollectionViewLayoutAttributes = attributesToReturn[i - 1]

这是功能:

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {

    var attributesToReturn:[UICollectionViewLayoutAttributes] = super.layoutAttributesForElementsInRect(rect) as! [UICollectionViewLayoutAttributes]

    for var i = 0 ; i < attributesToReturn.count ; i++
    {
        var currentLayoutAttributes: UICollectionViewLayoutAttributes = attributesToReturn[i]
        var previousLayoutAttributes: UICollectionViewLayoutAttributes = attributesToReturn[i - 1]
        var maximumSpacing: CGFloat = 50
        var origin = CGRectGetMaxX(previousLayoutAttributes.frame)
        if origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize().width
        {
            var frame: CGRect = currentLayoutAttributes.frame
            frame.origin.x = origin + maximumSpacing
            currentLayoutAttributes.frame = frame
        }
    }

    return attributesToReturn

}

我想这是因为起初没有i - 1对象..但我还能怎么做呢?

1 个答案:

答案 0 :(得分:1)

您可以重写代码,以便检查否定索引。

let origin: CGFloat
if i - 1 >= 0 {
    let previousLayoutAttributes = attributesToReturn[i - 1]
    origin = previousLayoutAttributes.frame.maxX
} else {
    origin = 0
}