iOS Swift,返回到视图控制器的同一个实例 [英] iOS Swift, returning to the same instance of a view controller

查看:70
本文介绍了iOS Swift,返回到视图控制器的同一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题,我有两个视图控制器A和B.视图控制器B有一个地图,上面有一个路线绘图。我此时可以在两个视图控制器之间前后移动,但每次加载时都会重置B视图控制器。我想这是因为我正在使用segues并且每次都在创建一个View控制器的新实例。

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.

我尝试使用以下代码来解决这个问题,但它仍然无法正常工作。视图加载正确,但视图控制器B仍在重置

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

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

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.

推荐答案

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

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

这样你就可以创建一次viewController,保存它,如果你想再次打开它,就会显示之前创建的一个。

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

这篇关于iOS Swift,返回到视图控制器的同一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆