Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : prepareForSegue with navigation controller

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 set data on the VC contained within the navigation controller?

like image 890
cedric petetin Avatar asked Feb 28 '15 23:02

cedric petetin


People also ask

How to Embed navigation controller Swift?

In your storyboard, select the initial view controller in your hierarchy. With this view controller selected, choose the menu item Editor -> Embed In -> Navigation Controller .

How to add a navigation controller in storyboard?

Under the View menu, select Utilities→Show Object Library. In the Object Library, find the Navigation Controller object (see Figure 4-7) and drag and drop it into the storyboard, to the left side of your existing view controller (Figure 4-6).

What is navigation controller Swift?

A navigation controller is a container view controller that manages one or more child view controllers in a navigation interface. In this type of interface, only one child view controller is visible at a time.


2 Answers

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 
like image 200
Wojtek Surowka Avatar answered Oct 06 '22 21:10

Wojtek Surowka


  1. Prepare the segue in the SendViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {     if segue.identifier == "segueShowNavigation" {         if let destVC = segue.destination as? UINavigationController,             let targetController = destVC.topViewController as? ReceiveViewController {             targetController.data = "hello from ReceiveVC !"         }     } } 
  2. Edit the identifier segue to "showNavigationController"

screenshot

  1. In your ReceiveViewController add

this

var data : String = ""  override func viewDidLoad() {     super.viewDidLoad()     print("data from ReceiveViewController is \(data)") } 

Of course you can send any other type of data (int, Bool, JSON ...)

like image 30
mattyU Avatar answered Oct 06 '22 23:10

mattyU