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

笑着哭i 提交于 2019-12-12 17:28:08

问题


I have a button in my SettingsViewController that when pressed, I want to present the same instance of my TimerViewController each time the button is pressed.

I think I have gotten fairly close with this post here, iOS Swift, returning to the same instance of a view controller. So if you could point me to saving the instance of TimerViewController, that would work the best.

This is the code I have right now -

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)

回答1:


the code you provided should work. if your SettingsViewController gets deallocated though the timerViewController also gets deallocated and recreated the next time you present it. so you have to make sure to save its instance at an appropriate location.

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)



回答2:


The best would be to save the ViewController somewhere , and get back to it . A way to "get back to it" : add

var tvc: TimerViewController? = nil

inside AppDelegate when you get to your Timer (the best would be when you left it , in viewDidDisappear)

you add :

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

then when you get to the setting , if you want to segue back to the timer

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

if you ask yourself why should you present it with the rootViewController (last line ) it is because you can present an already active viewController , this will not present an already active vc .



来源:https://stackoverflow.com/questions/33945151/swift-how-to-return-to-the-same-instance-of-my-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!