2015-07-10 83 views
-1

間距我試圖this Objective-C的答案轉換爲斯威夫特,但它總是在這條線崩潰:UICollectionViewLayout項目與斯威夫特

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對象,但我還能怎麼做?

+0

該鏈接中的兩個答案都在Swift中......無論如何,您試圖訪問索引-1處的項目,這是導致崩潰的原因。 – timgcarlson

回答

1

您可以重寫代碼,以檢查負指數。

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