-1

I tried to convert this Objective-C answer to Swift, but for it always crash on this line:

var previousLayoutAttributes: UICollectionViewLayoutAttributes = attributesToReturn[i - 1]

This is the function:

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 guess it's because at first there is no i - 1 object.. but how else can I do that?

Community
  • 1
  • 1
ytpm
  • 4,962
  • 6
  • 56
  • 113
  • Both of the answers in that link are in Swift already... in any case you are attempting to access an item at index -1, which is the reason for the crash. – timgcarlson Jul 10 '15 at 21:49

1 Answers1

1

You could rewrite your code so it checks for a negative index.

let origin: CGFloat
if i - 1 >= 0 {
    let previousLayoutAttributes = attributesToReturn[i - 1]
    origin = previousLayoutAttributes.frame.maxX
} else {
    origin = 0
}
Tomáš Linhart
  • 13,509
  • 5
  • 51
  • 54