简体   繁体   中英

Swift 1.2 - prepareForSegue targeting a View Controller embedded Navigation Controller

As in this question, I need to pass a value from a ViewController to another one, the second VC is embedded in navigation controller. I tried the answer to that question but value printed in console is always nil . Can't figure out what to do.

In First VC I have:

var dataToSend : String!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

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

        if segue.identifier == "toSecondVCSegue" {

            println("prepareForSegue occurred test value is: *\(dataToSend)*")

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

            targetController.receivedTest = dataToSend

        }
    }




    @IBAction func toSecondVCButtonTapped(sender: UIButton) {

        performSegueWithIdentifier("toSecondVCSegue", sender: nil)

        dataToSend = "passed"
    }

in the second I have:

var receivedTest : String!

    override func viewDidLoad() {
        super.viewDidLoad()

        println("in SecondViewController in viewDidLoad receivedTest is: *\(receivedTest)*")

    }

    override func viewWillAppear(animated: Bool) {

        println("in SecondViewController in viewWillAppear receivedTest is: *\(receivedTest)*")

    }


    override func viewDidAppear(animated: Bool) {

        println("in SecondViewController in viewDidAppear receivedTest is: *\(receivedTest)*")

    }

I think, the reason is you set value to dataToSend variable after calling performSegueWithIdentifier and so it stays always nil

Try changing your code as :

@IBAction func toSecondVCButtonTapped(sender: UIButton) {
    dataToSend = "passed"
    performSegueWithIdentifier("toSecondVCSegue", sender: nil)
}

This may help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM