iOS Swift, 返回同一个view controller实例

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

我有一个问题,我有两个视图控制器 A 和 B。视图控制器 B 有一张地图,上面绘制了一条路线。我现在可以在两个视图控制器之间来回移动,但是 B 视图控制器在每次加载时都会重置。我认为这是因为我正在使用 segues 并且它每次都在创建一个新的视图控制器实例。

我试过使用下面的代码来解决这个问题,但还是不行。视图加载正确,但视图控制器 B 仍在重置

@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)
}

我做错了什么,我该如何解决?我希望视图控制器 B 与地图和路线一起保留在内存中,因此当用户 returns 时,他不必再次输入所有信息。

您应该在 class 类型的 UIViewController 中创建一个变量,并将您的代码更改为以下内容:

@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)
}

这样你就创建了一次viewController,保存它,如果你想再次打开它,请出示之前创建的那个。