Search code examples
iosswiftuicollectionviewindexpath

UICollectionView Getting indexPath in prepareForSegue


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
   }
}

Solution

  • 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)
        }