3

Im passing data from one CollectionViewController to a detail ViewController. Everything seems to be working, but the "prepareForSegue is happening before the "didSelectItemAtIndexPath" so it's passing the data of the item I selected the last time not the one I'm selecting right now.

This is my wrong code for the collectionViewController

var cellSelected : Int = 0

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    cellSelected = indexPath.row
    println("Did select!")
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "identifierName" {
        var secondScene = segue.destinationViewController as detailVC

        secondScene.authorDetail = data[cellSelected].userOfImg
        secondScene.likesDetail = data[cellSelected].likesInImg
        secondScene.imageDetail = data[cellSelected].imgPath
        println("Prepare for segue")
    }
}

The result in the debug area is:

  1. Prepare for segue
  2. Did select!
Avi Mose
  • 97
  • 10
  • 1
    See [this similar question](http://stackoverflow.com/q/18165684/1348195) and [that similar question](http://stackoverflow.com/questions/13235579/how-to-call-didselectrowatindexpath-before-prepareforsegue) to get an idea. – Benjamin Gruenbaum Apr 11 '15 at 22:24
  • Thank you so much @benjamin-gruenbaum, but this examples are using a tableView and for what I've seen in that case I can use the `indexPath.row` inside the `prepareForSegue`. That's why in my code i tried to use the `didSelectItemAtIndexPath`. – Avi Mose Apr 11 '15 at 23:09

2 Answers2

3

I've found a solution for this. It's to use shouldSelectItemAtIndexPath instead of didSelectItemAtIndexPath. Doing this the shouldSelectItemAtIndexPath will be executed before the prepareForSegue and will fix the problem of sending the data of the item you are selecting and not the one selected the last time.

Avi Mose
  • 97
  • 10
  • There is no need to set cellSelected, just use sender in prepareForSegue to get indexPath. – imike Apr 18 '15 at 11:02
1

Right solution

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifierName" {
        var secondScene = segue.destinationViewController as detailVC
        let cell = sender as UICollectionViewCell
        let indexPath = collectionView.indexPathForCell(cell)
        secondScene.authorDetail = data[indexPath.row].userOfImg
        secondScene.likesDetail = data[indexPath.row].likesInImg
        secondScene.imageDetail = data[indexPath.row].imgPath
        println("Prepare for segue")
    }
}
imike
  • 5,515
  • 2
  • 37
  • 44