Search code examples
swiftuicollectionviewsegue

why do I get two consecutive viewcontrollers when carrying out segue to show details


when I click on the uicollectionViewCell then I come to a ViewController that is empty and a split second later a new ViewController is createdvshowing the data correctly. Going back I have to click the back button twice to navigate back to the original viewController. In the MainStoryboard I have a "show detail" segue implemented. What is going on here? What do I have to check?? Here is the code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell

    key = cell.keyImage.image

    performSegue(withIdentifier: "showKeyDetails", sender:self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showKeyDetails"{
        if let destVC = segue.destination as? KeyDetailViewController{
            if key != nil{
                destVC.key = key
            }
        }
    }
}

Solution

  • You wired your segue from the collectionView cell. So, when you select the cell, a segue fires, and then performSegue creates a second segue.

    To fix this, you can either:

    1. Remove the performSegue call, remove the didSelectItem function and update your prepare(for:sender:) function to find the key:

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if segue.identifier == "showKeyDetails"{
              if let destVC = segue.destination as? KeyDetailViewController,
                 let cell = sender as? CollectionViewCell,
                 let key = cell.keyImage.image
              {
                  destVC.key = key
              }
          }
      }
      

      OR:

      2) Wire the segue from the viewController icon at the top of the VC instead of from the cell.