Swift : prepareForSegue with navigation controller

cedric petetin picture cedric petetin · Mar 1, 2015 · Viewed 43.8k times · Source

I am developing an iOS application in Swift.

I want to send data from a view to an other one, using the prepareForSegue function.

However, my target view is preceded by a navigation controller, so it doesn't work.

How can I do this please ?

Answer

Wojtek Surowka picture Wojtek Surowka · Mar 1, 2015

In prepareForSegue access the target navigation controller, and then its top:

let destinationNavigationController = segue.destination as! UINavigationController
let targetController = destinationNavigationController.topViewController

From the target controller you can access its view and pass data.

In old - now obsolete - versions of Swift and UIKit the code was slightly different:

let destinationNavigationController = segue.destinationViewController as UINavigationController
let targetController = destinationNavigationController.topViewController