-1

I am trying to create a UICollectionViewFlowLayout subclass and i am getting ambiguous reference to member 'subscript' error when i try to return the layoutAttributesForItem: import UIKit

class FLCollectionViewFlowLayout: UICollectionViewFlowLayout {

    var items = 0
    let CELL_HEIGHT : CGFloat = 306.0
    let CELL_WIDTH  : CGFloat  = 219.0
    var cellInformation = Dictionary<NSIndexPath,UICollectionViewLayoutAttributes>()
    var contentSize = CGSize.zero

    override var collectionViewContentSize: CGSize {
        return self.contentSize
    }

    override func prepare() {
        super.prepare()
        print("preparing layout")
        items = 20
        let sections = self.collectionView?.numberOfSections
        var section = 0
        var item = 0
        var indexPath = NSIndexPath()
        var contentWidth : CGFloat = 0.0
        let contentHeight : CGFloat = CELL_HEIGHT + self.sectionInset.top + self.sectionInset.bottom
        while section < sections! {
            while item < (self.collectionView?.numberOfItems(inSection: section))! {
                indexPath = NSIndexPath(item: item, section: section)
                let xPos = CGFloat(item) * CELL_WIDTH
                let yPos = CGFloat(section) *  CELL_HEIGHT
                let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)
                cellInformation[indexPath] = cellAttributes
                item+=1
            }
            contentWidth = CGFloat((self.collectionView?.numberOfItems(inSection:section))!) * CELL_WIDTH
            section+=1
        }
        self.contentSize = CGSize(width: contentWidth, height: contentHeight)

    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributesInRect = [UICollectionViewLayoutAttributes]()

        for cellAttributes in cellInformation.values {
            if rect.intersects(cellAttributes.frame) {
                attributesInRect.append(cellAttributes)
            }
        }

        return attributesInRect
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {

        return cellInformation[indexPath]! // <---- This is where i get the error

    }

}

Any suggestion would be greatly appreciated .

cromanelli
  • 576
  • 1
  • 5
  • 21

1 Answers1

1

In Swift 3 NSIndexPath has been replaced with native struct IndexPath

Change

...
var cellInformation = Dictionary<IndexPath,UICollectionViewLayoutAttributes>()
...
var indexPath = IndexPath()
...
indexPath = IndexPath(item: item, section: section)
...
let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
vadian
  • 274,689
  • 30
  • 353
  • 361