iOS Swift, returning to the same instance of a view controller

霸气de小男生 提交于 2019-11-30 19:06:56

问题


I have a problem, where I have two view controllers A and B. View controller B has a map, with a route draw on it. I can move back and forwards between the two view controllers at the moment, but the B view controller is reset every time it loads. I think this is because I am using segues and it is creating a new instance of a View controller every time.

I have tried using the following code to solve this issue, but it is still not working. The views load correctly, but view controller B is still being 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 can I fix it? I want view controller B to stay in the memory along with the map and the route, so when a user returns he doesn't have to enter all of the information again.


回答1:


You should 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)
}

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



来源:https://stackoverflow.com/questions/29993085/ios-swift-returning-to-the-same-instance-of-a-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!