Home > Software design >  Swift & Navigation : How do I replace a ViewController and also send some parameters?
Swift & Navigation : How do I replace a ViewController and also send some parameters?

Time:10-21

How do I replace a ViewController and also send some parameters?

With the code below, I can only push another ViewController into my current Navigation Stack. Can we just pop and push another one immediately? Or is there an official to replace for good? Please kindly show me. Thank you.

Perform Segue

performSegue(withIdentifier: "ToNewViewController", sender: self)

Prepare Segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! NewViewController
        destinationVC.params = params
    }

CodePudding user response:

If you have a navigation controller as your app window root , then you can manage all viewControllers

var vcs = self.navigationController!.viewControllers // get all vcs
vcs = vcs.dropLast() // remove last vc
let vc = // create new VC
vcs.append(vc) // append it

Then alter that array and set it back like this

self.navigationController!.setViewControllers(vcs,animated:true)

OR

You can get the top presented vc with this , then add a method to that vc to do the data replacement and refresh of your UI

  • Related