IOS Swift reverting to the same view controller instance

I have a problem where I have two view controllers A and B. View controller B has a map with a route trace on it. I can navigate back and forth between the two view controllers for now, but the B view controller is reset every time it is loaded. I think this is because I am using segues and creates a new instance of the View controller every time.

I tried using the following code to solve this problem, but it still doesn't work. Views are loading correctly, but controller B's view is still reset

@IBAction func mapButton(sender: AnyObject){
        let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
        self.presentViewController(vc, animated: true, completion: nil)
}

      

What am I doing wrong and how do I fix it? I want the view controller B to stay in memory along with the map and route, so when the user returns, he doesn't have to re-enter all the information.

+2


source to share


1 answer


You must create a variable in your class of type UIViewController and change your code to the following:

@IBAction func mapButton(sender: AnyObject){
    if yourVariable == nil {
        let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
        yourVariable = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
    }
    self.presentViewController(yourVariable, animated: true, completion: nil)
}

      



This way you create the viewController once, save it, and if you want to open it again, present the previously created one.

+3


source







All Articles