【问题标题】:Swift: How to return to the same instance of my UIViewControllerSwift:如何返回到我的 UIViewController 的同一个实例
【发布时间】:2015-11-26 18:34:31
【问题描述】:

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

我想我已经很接近这篇文章了,iOS Swift, returning to the same instance of a view controller。因此,如果您能指出我保存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)

【问题讨论】:

  • 代码有什么问题?
  • 我需要一种方法来回到TimerViewController 的同一个实例。我有一个先实例化的好方法,但我不知道如何返回到同一个实例。
  • 您的代码应该可以工作。
  • 但这正是您发布的代码的作用!问题是,如果您的 SettingsViewController 本身被解除,则保存的 TimerViewController 实例也会被释放并在下次重新创建...
  • @AndréSlotta 我认为你是对的。如何确保SettingsViewController 不会被解雇?我的理解是instantiateViewControllerWithIdentifier("timer") 每次都会创建一个新实例。

标签: ios swift uitableview uiviewcontroller instance


【解决方案1】:

您提供的代码应该可以工作。如果您的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)

【讨论】:

  • 非常感谢!我解散了 TimerViewController,它解决了我创建 SettingsViewController 的新实例的问题。实例化正在工作,但由于正在创建新的 SettingsViewController,它正在再次运行。
【解决方案2】:

最好的办法是将 ViewController 保存在某个地方,然后再使用它。 一种“回到它”的方法: 添加

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)

如果你问自己为什么要使用 rootViewController(最后一行)呈现它,那是因为你可以呈现一个已经激活的 viewController,这不会呈现一个已经激活的 vc。

【讨论】:

  • 感谢您的回答,我确实设法让它与接受的响应一起工作。如果遇到这个问题,我希望这可以帮助其他人!
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多