-2

I'm trying to access the indexPath.row variable from my collectionView in my prepareForSegue function. I have the following code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let selectedIndex = collectionView.indexPathsForSelectedItems() as NSIndexPath
    //let myIndexPath = self.collectionView.indexPathForCell(cell: LocalFeedCollectionViewCell.self)

    if (segue.identifier == "toFullImage")
    {
        var fullImageVC: FullImageViewController = segue.destinationViewController as FullImageViewController
        fullImageVC.imageTitle = self.imageTitles[selectedIndex.row]
    }
}

I'm receiving the following error for selectedIndex - '(UICollectionView, numberOfItemsInSection: Int) -> Int' does not have a member named 'indexPathsForSelectedItems'. In Objective-C I see the following solution

NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];

but I'm not sure how to implement it in swift/if it would work.

Thanks

Andrew Monshizadeh
  • 1,784
  • 11
  • 16
Ben
  • 1
  • 1
  • I think I may have gotten around the problem by making a variable a variable "var rowPath: Int = 0" and then setting it equal indexPath.row. Then I can write " fullImageVC.imageTitle = self.imageTitles[rowPath]" – Ben Jan 06 '15 at 03:06
  • Is the error you have in your question actually generated within that piece of code? I don't see any reference to `numberOfItemsInSection` in the code you provided. – Andrew Monshizadeh Jan 06 '15 at 03:09
  • Yes the error was found on the "let selectedIndex" line – Ben Jan 06 '15 at 14:21

2 Answers2

1

One obvious problem is that indexPathsForSelectedItems() does not return something that can be cast to an NSIndexPath. It returns an array. If you are trying to cast down to an array of index paths, you need to cast down to [NSIndexPath], not to NSIndexPath.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I saw that too, but it didn't seem to match up to the type error in the question. Though, I'm not convinced that type error is actually within that function (since it references `numberOfItemsInSection`). – Andrew Monshizadeh Jan 06 '15 at 03:09
  • It doesn't really matter. There is a compile error on that line, and this is the reason for it. If you try his code and change his `NSIndexPath` to `[NSIndexPath]` the compile error on that line does in fact go away. There may be other problems with his code down the line - I don't know - but this is the answer to that one. – matt Jan 06 '15 at 03:10
0

The sender parameter is collection view's cell. So first cast it to the UICollectionViewCell and then ask indexPath from the collection view. Here is a sample

if let cell = sender as? UICollectionViewCell {
    if let indexPath = collectionView.indexPathForCell(cell) {
        // use indexPath here
    }
}
mustafa
  • 15,254
  • 10
  • 48
  • 57