41

I'm trying to push data from one viewController to another. I've connected a viewController to another ViewController's navigationController and then set the identifier to "showItemSegue". I get an error in these two lines:

var detailController = segue.destinationViewController as ShowItemViewController
detailController.currentId = nextId!

Image illustration:

enter image description here

The code:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


    nextId = itemArray?.objectAtIndex(indexPath.row).objectForKey("objectId") as? NSString

    self.performSegueWithIdentifier("showItemSegue", sender: self)

}


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

    if (segue.identifier == "showItemSegue") {
        var detailController = segue.destinationViewController as ShowItemViewController
        detailController.currentId = nextId!
    }

}
vacawama
  • 150,663
  • 30
  • 266
  • 294
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

1 Answers1

77

The destination view controller of the segue is the UINavigationController. You need to ask it for its top view controller to get to the real destination view controller:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showItemSegue" {
        let navController = segue.destination as! UINavigationController
        let detailController = navController.topViewController as! ShowItemViewController
        detailController.currentId = nextId!
    }
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Thanks, this solution seems to work fine with swift 3 – mic Feb 27 '17 at 09:50
  • Awesome! This helped me with modal dialogs that were embedded in a Navigation Controller - without a visible navigation bar - in order to have a navigation bar (+ back button) in the next segued view controller. Due to the rather complicated setup I was a bit anxious.. But it works fine :) – Colibri May 16 '18 at 08:33
  • In messing around with this a little I found that if you create the segue between the two view controllers and bypass the navigation controller on the storyboard, then the code in the question works just fine, and you still have the back button presented in the buttonbar. If you have the segue between the view controller and the navigation controller then the answer provided by @vacawama works perfectly and there is no back button provided in the buttonbar. May just be a matter of preference. – Scooter Nov 24 '20 at 03:08