pprevalon pprevalon - 4 months ago 12
Swift Question

Swift - How to pass UInavigationController and also pass variables

What is the best way to pass a UInavigationController and also pass variables to a new viewController. I know how to do one or the other but not both at the same time. Thank you in advance

this is my current code


let vc = storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as! UINavigationController
let posts = self.postList[indexPath.row]

//this is the var that i want to past
//vc.previousViewMessageId = posts.postKey

self.presentViewController(vc, animated: true, completion: nil)



If I understand you correctly, you have a view controller that can present a second VC. And this VC is embedded in a UINavigationController. What you don't know how to do, is to pass data from the first VC, to the navigation controller, then to the second VC.

Here is a brute force solution. It's not beautiful, but it works anyway.

Make your own UINavigationController subclass:

class DataPasserController: UINavigationController {
    var previousViewMessageId: SomeType?
    override func viewDidLoad() {
        if let vc = self.topViewController as? YourSecondViewController {
            vc.previousViewMessageId = self.previousViewMessageId

Now you can add a navigation controller in the storyboard, set its class to DataPasserController, and connect the second VC to it as its root view controller.

Now suppose you have got an instance of DataPasserController by calling instantiateViewControllerWithIdentifier, you can do this:

yourDataPasserControllerInstance.previousViewMessageId = posts.postKey

And present the instance!