Swift: 如何 return 到我的 UIViewController 的同一个实例

Swift: How to return to the same instance of my UIViewController

我的 SettingsViewController 中有一个按钮,当按下该按钮时,我想在每次按下该按钮时显示我的 TimerViewController 的相同实例。

我想我已经很接近这里的 post,。因此,如果你能指出我保存 TimerViewController 的实例,那将是最好的。

这是我现在拥有的代码 -

var yourVariable : UIViewController!

if yourVariable == nil {
   let storyboard = UIStoryboard(name: "Main", bundle: nil)
   yourVariable = storyboard.instantiateViewControllerWithIdentifier("timer") as! TimerInterface
        }
presentViewController(yourVariable, animated: true, completion: nil)

最好将 ViewController 保存在某处,然后再返回。 "get back to it" 的一种方式: 添加

var tvc: TimerViewController? = nil

在 AppDelegate 中 当你到达你的计时器时(最好是当你离开它时,在 viewDidDisappear 中)

您添加:

(UIApplication.sharedAplication().delegate as! AppDelegate).tvc = self

然后当你到达设置时,如果你想继续回到计时器

let tvc = (UIApplication.sharedAplication().delegate as! AppDelegate).tvc
(UIApplication.sharedApplication().delegate? as! AppDelegate).window?.rootViewController?.presentViewController(tvc, animated: true , completion: nil)

如果你问自己为什么要用根ViewController(最后一行)显示它,那是因为你可以显示一个已经激活的 viewController ,这不会显示一个已经激活的 vc.

您提供的代码应该可以工作。如果您的 SettingsViewController 被释放,尽管 timerViewController 也会在您下次展示它时被释放并重新创建。所以你必须确保将其实例保存在适当的位置。

var timerViewController: TimerViewController!

if timerViewController == nil {
   let timerViewController = UIStoryboard(name: "Main", bundle: nil)
   yourVariable = storyboard.instantiateViewControllerWithIdentifier("timer") as! TimerInterface
}

presentViewController(timerViewController, animated: true, completion: nil)