1

For my collection view I use didSelectItemAt to call performSegue. My problem is that the sender is my vc and not the cell itself. So in prepareForSegue, I get an error, because I can't convert the vc to my cell type.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   performSegue(withIdentifier: "collectionSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let destinationVC = segue.destination as? ImageViewController {
      let cell = sender as! ImageCollectionViewCell 
      let indexPath = imageCollectionView.indexPath(for: cell)
      destinationVC.buttonTag = indexPath?.row
   }
}
squarehippo10
  • 1,855
  • 1
  • 15
  • 45

2 Answers2

1

You can set sender as anything you want. This may help:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       let cell = collectionView!.cellForItemAtIndexPath(indexPath) as! ImageCollectionViewCell
       performSegue(withIdentifier: "collectionSegue", sender: cell)
    }
0

try this

var currentIndex = 0
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   self.currentIndex = indexPath.row
   performSegue(withIdentifier: "collectionSegue", sender: self)
   //let cell = sender as! ImageCollectionViewCell
   //performSegue(withIdentifier: "collectionSegue", sender: cell)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "collectionSegue" {
    if let destinationVC = segue.destination as? ImageViewController {
        //let indexPath = imageCollectionView.indexPath(for: cell)
        //let indexPath = imageCollectionView.indexPath(for: sender as! ImageCollectionViewCell)
        destinationVC.buttonTag = self.currentIndex
    }
  }
}
Andres Gomez
  • 458
  • 3
  • 12