Swift:如何返回到我的UIViewController的同一个实例
我在我的SettingsViewController
中有一个按钮,当按下时,我想在每次按下按钮时呈现我的TimerViewController
的相同实例。
我想我已经非常接近这篇post, iOS Swift,返回到视图控制器的同一个实例 。 所以,如果你能指出我保存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)
你提供的代码应该工作。 如果您的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)
最好的方法是将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。